[英]How to handle the event when the selected item changes in an HTML select
I currently have two Ruby selects: one for categories and the other one for subcategories. 我目前有两个Ruby选择:一个用于类别,另一个用于子类别。 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?
是否有“红宝石方式”,或者我必须使用JavaScript?
Thanks, Brian 谢谢,布莱恩
You have to use at least some JavaScript. 您必须至少使用一些JavaScript。 In jQuery, you can do this:
在jQuery中,您可以执行以下操作:
$(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: 在您的CategoriesController中,您的show操作应响应format.js,这应使子类别部分呈现:
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 %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.