【问题标题】:How do I make a form field the same as another field?如何使表单域与另一个域相同?
【发布时间】:2013-07-08 20:54:03
【问题描述】:

我有一个表单,允许用户编辑员工在公司的历史记录。

我想这样当用户更改第一个条目的“到位置”下拉菜单时,它会将下一个条目中的“从位置”下拉菜单更改为等于它。

 <% f.fields_for :employee_position_histories do |emp_pos_his| %>
    <table class="crud-form">
      <tr>
        <td><%= f.label :from_position_id,  " Start Position: " %></td>
        <td><%= f.collection_select :from_position_id, Position.active, :id, :title, { :prompt => ' Select a Position ' }, { :class => 'clean average' } %></td>
      </tr>
      <tr>  
        <td><%= f.label :to_position_id,  " To Position: " %></td>
        <td><%= f.collection_select :to_position_id, Position.active, :id, :title, { :prompt => ' Select a Position ' }, { :class => 'clean average' } %></td>
      </tr> 
      <tr>
        <td><%= f.label :started_at, "Start Date: "%></td>
        <td><%= f.date_picker :started_at, :class => "clean average" %>
      </tr> 
      <tr>
        <td><%= f.label :ended_at, "End Date: "%></td>
        <td><%= f.date_picker :ended_at, :class => "clean average" %>
      </tr>
      <hr>
    </table> 
<% end %>

我不确定执行此操作的最佳方法。我的一位同事说要使用 jscript,但我也不知道该怎么做。

【问题讨论】:

    标签: javascript html ruby-on-rails ruby forms


    【解决方案1】:

    您可以使用 jQuery 来执行此操作:

    var fromBox = $("#from");
    fromBox.change(function () {
        $("#to").val(fromBox.val());
    });
    

    只需将“#to”和“#from”替换为您的 ID

    jsfiddle:http://jsfiddle.net/hummlas/m87ap/

    【讨论】:

    • 非常感谢您的帮助。我确实有另一个问题是,此表格可以从员工到员工的条目数量不同。因此,ID 不是静态的。下面是 from id 和 to id 的示例。 employee_employee_position_histories_attributes_0_to_position_id employee_employee_position_histories_attributes_1_from_position_id。有没有办法动态更改 id 名称?
    • 如果您知道如何为下拉列表生成 ID 的逻辑,那么在 javascript 中动态创建它们应该不是问题。
    【解决方案2】:

    我不熟悉 ruby​​ 语法,所以我不知道您选择的 id 使用什么。
    这是一种不使用 jQuery 的方法:

    var fromBox = document.getElementById("from");
    
    fromBox.addEventListener('change',function() {
         document.getElementById("to").value = fromBox.value;
    }, false);
    

    Jsfiddle:http://jsfiddle.net/h5gew/12/

    【讨论】:

      猜你喜欢
      • 2021-11-08
      • 2017-08-26
      • 1970-01-01
      • 1970-01-01
      • 2019-09-08
      • 2021-01-29
      • 2015-12-26
      • 2011-12-11
      • 1970-01-01
      相关资源
      最近更新 更多