2015-09-07 46 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。类似于您的其他线路。