jquery - show next select box based on previous selection -


<%= f.collection_select :category, category.all, :id, :name, {prompt: true}      <%= f.collection_select :sub_category, subcategory.all, :id, :name, {prompt: true} %> 

i want show category specific sub_category based on category selection. how achieve in ruby on rails using jquery.

yes possible. on category drop down change event have call js request , request return sub categories based on category select

$("#category_id").change(function(){   var category_id = $('#category_id').val()   url = "/some_url?category_id=" + category_id   $.get(url, function(data) {     var set_sub_category;     set_sub_category = $("#sub_category_id");     set_sub_category.empty();     opt = $("<option/>");     opt.attr("value", "");     opt.appendto(set_sub_category);     opt.text("---select sub categories---");     $.each(data, function(index, value) {       var opt;       opt = $("<option/>");       opt.attr("value", value[1]);       opt.text(value[0]);       opt.appendto(set_sub_category);     });   }); }); 

controller likes

def some_url   @data = []   @category = category.find_by(id: params[:category_id])   if @category    @data = @category.sub_categories.map{|b| [b.name,b.id]}   end   render json: @data end 

Comments