2015-09-07 45 views
0

下面是一個的jsfiddle什麼,我試圖完成:動態下拉菜單Ruby on Rails的的form_for

https://jsfiddle.net/sherali/jkw8fxzf/12/

HTML:

<select id="first-choice"> 
    <option value="English">English</option> 
    <option value="Spanish">Spanish</option> 
</select> 

<select id="second-choice"> 
    <option value="Spanish">Spanish</option> 
    <option value="English">English</option> 
</select> 

JS:

var $secondOption= $('#second-choice>option').clone(); 

$("#first-choice").change(function() { 
    var userSelected = $(this).val(); 

    $('#second-choice').html($secondOption); 

    // $("#second-choice").val(userSelected) 
    $('#second-choice option[value="'+userSelected+'"').remove() 
}); 

我試圖採取上面的代碼工作,並將其轉換爲具有相同行爲的東西使用軌道時的form_for如下方法:

<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %> 
<%= f.label :natives_language, "Native Language" %> 
<%= f.select :natives_language, [ 'Spanish', 'English'], :class => "first-choice" %> 

<%= f.label :next_language, "I Want To Learn" %> 
<%= f.select :next_language, [ 'English', 'Spanish'], :class => "second-choice" %> 
<% end %> 

哪產生以下HTML:

<label for="user_natives_language">Native Language</label> 
<select id="user_natives_language" name="user[natives_language]"> 
    <option value="English">English</option> 
    <option value="Spanish">Spanish</option> 
</select> 

<label for="user_next_language">I Want To Learn</label> 
<select id="user_next_language" name="user[next_language]"> 
    <option value="Spanish">Spanish</option> 
    <option value="English">English</option> 
</select> 

它不象的類第一選擇和第二選擇被添加某種原因。關於如何使這個工作的任何想法?

感謝和問候。

回答

1

doc for select,你可以看到它接受以下命令參數:

select(object, method, choices = nil, options = {}, html_options = {}, &block) 

既然你想傳遞什麼顯然是一個HTML選項,你可能想使用類似

<%= f.select :next_language, [ 'English', 'Spanish'], {}, {:class => "second-choice"} %> 

有效地傳遞一個空的散列作爲選項,然後將您的自定義類作爲html_options。類似於您的其他線路。