【问题标题】:How to iterate through dynamically generated combo boxes with jquery如何使用 jquery 遍历动态生成的组合框
【发布时间】:2014-06-24 14:44:08
【问题描述】:

我正在使用 html.erb 在 rails 应用程序中生成视图。

我正在使用 "each do | |" 生成组合框

如何使用 jquery 遍历动态生成的组合框的值,并在组合框的任何值相同时提醒用户。

    <table class="holiday_allowance_schedule tabular_data_cell">
  <thead>
    <th class="years_from_accrual_start">
      <%= a(:company_policy, :years_from_accrual_start) %>
    </th>
    <th class="months_allocated"><%= a(:company_policy, :days_allocated) %></th>
    <th></th>
    <th></th>
  </thead>
  <tbody id="schedule_table">
    <% @policies.holiday_allocation_schedule.keys.sort.each do |year| -%>
      <tr id="<%= year %>">
        <% days = @policies.holiday_allocation_schedule[year] %>

        <td><%= select_tag("holiday_schedule[][year]", options_for_select(holiday_allocation_years_options, year)) %></td> #combo boxes with years

        <td><%= select_tag("holiday_schedule[][days]", options_for_select(holiday_allocation_days_options, days)) %></td>
        <td class="actions"><%= add_icon %></td>
        <td class="actions"><%= remove_icon %></td>
      </tr>
    <% end -%>
  </tbody>
</table>

例如:有五个组合框

1 年

2 年

3 年

4 年

5 年

如果用户在任意两个或更多组合框中选择“3 年”,则必须显示警报

如何使用 jquery 或使用 erb 本身来完成此操作

【问题讨论】:

    标签: jquery ruby-on-rails erb


    【解决方案1】:

    为所有组合框绑定一个 change() 监听器,在那里进行检查。

    $('select').change(function(){
       var values = []
       $.each($('select'), function(idx, sel){
         if(values.index(sel.val()) != -1){
           alert('same value selected')
         }else{
           values.push(sel.val())
         }
       })
    })
    

    【讨论】:

    • 请在此答案中添加其他信息,例如一些示例代码。
    • 抱歉nickcen,我听不懂你的回答
    • @YasirAzzu 逻辑如下。您应该将 change() 侦听器绑定到所有选择输入。当任何选择输入值发生变化时,将调用侦听器。监听器内部的逻辑是取回所有select的值,看是否有两个select具有相同的值。
    • 谢谢 nickcen,我明白你的回答。成功了,我已经解决了我的问题。
    猜你喜欢
    • 2020-05-22
    • 2013-06-29
    • 1970-01-01
    • 1970-01-01
    • 2020-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多