samedi 19 novembre 2016

jQuery script for making checkbox appear based on if selected category contains true boolean

I am trying to check if there is a boolean value of true within the subcategory I select in a dropdown which in turn would make a checkbox appear.

In my form partial to create a new post I have to select a Category and a SubCategory accordingly. My SubCategories are seeded like so SubCategory.where(name: 'DB', service_type: true, category_id: 1_category.id).first_or_create.

The current javascript I am trying to make work is

$(document).ready(function () {

    $("#service-select").hide();

    $('#subcategory-select').change(function () {
        var subcatServ = $(this).val();
        $('#service-select').hide();
        if (subcatServ === "Persons") {
            $('#service-select').show();
        }
    });    
});

#select-service is where the checkbox and #subcategory-select is the selected subcategory. I currently use this JS to make SubCategories and the associated ID appear and be saved when I select their parent Category:

$(document).ready(function() {
  var subcat;
  subcat = $('#subcategory-select').html();
  return $('#category-select').change(function() {
    var cat, options;
    cat = jQuery('#category-select').children('option').filter(':selected').text();
    options = $(subcat).filter("optgroup[label='" + cat + "']").html();
    if (options) {
      return $('#subcategory-select').html(options);
    } else {
      return $('#subcategory-select').empty();
    }
  });
});

HTML:

  <%= form_for @post do |f| %>
  ....
  ....
  <p>
        <%= f.label :category_id%>
        <%= f.collection_select(:category_id, Category.all, :id, :name,    
                       { prompt: 'Select a category' }, { id: 'category-select' }) %>
  </p>
  <p>
        <%= f.label :subcategory_id%>
        <%= f.grouped_collection_select :subcategory_id, Category.all, :sub_categories, 
                  :name, :id, :name, { prompt: 'Select a sub category' },
                                                       { id: 'subcategory-select' } %>
   </p>
   <p>
           <%= f.label "checkbox"%>
           <%= f.check_box :serivce_type, id:'service_select' %> <!--work on-->
   <p>
  <%end%>

I'm unsure on how to do this and have thought about and researched how for ~30mins, any help would be appreciated.




Aucun commentaire:

Enregistrer un commentaire