简体   繁体   English

当选定的项目在HTML select中更改时如何处理事件

[英]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.

相关问题 选择HTML选择/下拉列表中的项目时会触发什么事件? - What event fires when item in HTML select/dropdown list is selected? 仅选择一个项目时如何处理多个项目的选择 - How to handle a select with multiple items when only one item is selected 在中选择项目时重新加载页面 <select> -HTML - reload page when item selected in <select> - HTML 在选择项上使用选定属性时,未触发jQuery更改事件 - Jquery change event not fired when using selected attribute on select item 选择选择框中的任何项目时,如何在jQuery中触发事件? - How do I trigger a event in jQuery when any item in a select box is selected? 从所选项目中删除和删除项目时,如何在反应选择中捕获添加和删除事件? - How to catch add and remove event in react-select when andding and removing item from selected? 如何在更改事件(选择框)上获取所选项目的索引? - how to get index in selected item on change event (select box)? 当“不相关”的html select元素未选择任何选项时,如何退出jQuery事件? - How can I exit from a jQuery event when an “unrelated” html select element has had no option selected? HTML触发事件 <select>再次选择相同条目时显示 - Trigger event in HTML <select> box when the same entry is selected again 当所选项目更改为下拉菜单时如何执行查询 - How to execute a query when selected item changes for a drop down
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM