2013-07-08 15 views
0

我有一個表格,允許用戶編輯公司員工的歷史記錄。如何使表單域與其他域相同?

我想這樣做當用戶更改第一個條目的「到位置」下拉菜單時,它會將下一個條目中的「從位置」下拉菜單更改爲等於它。

<% 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,但我不知道該怎麼做。

回答

0

您可以使用jQuery來做到這一點:

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

只需更換 「q若要」 和 「#from」 與您的ID

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

+0

的幫助真棒感謝。我還有另外一個問題,就是這個表格可能有不同數量的從員工到員工的條目。因此,這些ID不是靜態的。這是一個從id和a到id的例子。 employee_employee_position_histories_attributes_0_to_position_id employee_employee_position_histories_attributes_1_from_position_id。有沒有辦法動態改變id名稱? – Maedar

+0

如果您知道如何爲下拉生成ID的邏輯,在javascript中動態創建它們應該不成問題。 –

0

我不熟悉紅寶石語法,所以我不能告訴你用什麼選擇ID。
這裏有一個辦法做到這一點沒有jQuery的:

var fromBox = document.getElementById("from"); 

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

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