How to handle the event when the selected item changes in an HTML select
I currently have two Ruby selects: one fo开发者_如何学Gor categories and the other one for subcategories. As you may anticipate, the second one has to update itself every time the first one changes.
For example, if I select from the first one the category "Sports", the second select should load all the sports.
How can I handle that "index change" event? Is there a "ruby way" or I have to use javascript?
Thanks, Brian
You have to use at least some JavaScript. In jQuery, you can do this:
$(document).ready(function(){
$('#first-select').change(function(){
$('#second-select').load('/categories/2');
});
});
In your CategoriesController, your show action should respond to format.js, which should render a subcategories partial:
class CategoriesController
...
def show
@subcats = SubCategory.find_all_by_parent_category(params[:id])
...
respond_to |format|
...
format.js { render :partial => "subcategories", :locals => { :subcats => @subcats } }
end
end
and your subcategories partial:
<% subcats.each do |subcat| %>
<option value="<%= subcat.value %>"><%= subcat.text %></option>
<% end %>
精彩评论