以下是我试图完成的JSFiddle:
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()
});
我尝试使用上面的代码,并使用下面显示的rails 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>
由于某种原因,看起来并没有添加第一选择和第二选择。有关如何使其工作的任何想法?
谢谢和问候。
答案 0 :(得分: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传递。类似于你的另一条线。