[英]Disable Drop Down Options Once Chosen In Other Dropdown in a Form for Rails
我正在尝试创建一个包含下拉列表的表单,每个下拉列表都使用相同的选项; 但是我希望每个选项只能选择一次。 我该如何实现?
这是我想要的表单的一般代码:
<div id="form">
<%= form_for :character, url: characters_path do |f| %>
<p>
<%= f.label :first_stat, "First Stat: " %>
<%= f.select :first_stat, options_for_select([" ","strength","dexterity","constitution","intelligence","wisdom","charisma"], disabled: " ", selected: " ") %>
</p>
<p>
<%= f.label :second_stat, "Second Stat: " %>
<%= f.select :second_stat, options_for_select([" ","strength","dexterity","constitution","intelligence","wisdom","charisma"], disabled: " ", selected: " ") %>
</p>
<p>
<%= f.label :third_stat, "Third Stat: " %>
<%= f.select :third_stat, options_for_select([" ","strength","dexterity","constitution","intelligence","wisdom","charisma"], disabled: " ", selected: " ") %>
</p>
<p>
<%= f.label :fourth_stat, "Fourth Stat: " %>
<%= f.select :fourth_stat, options_for_select([" ","strength","dexterity","constitution","intelligence","wisdom","charisma"], disabled: " ", selected: " ") %>
</p>
<p>
<%= f.label :fifth_stat, "Fifth Stat: " %>
<%= f.select :fifth_stat, options_for_select([" ","strength","dexterity","constitution","intelligence","wisdom","charisma"], disabled: " ", selected: " ") %>
</p>
<p>
<%= f.label :sixth_stat, "Sixth Stat: " %>
<%= f.select :sixth_stat, options_for_select([" ","strength","dexterity","constitution","intelligence","wisdom","charisma"], disabled: " ", selected: " ") %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
</div> <!-- END OF FORM -->
显然,这不会阻止多次选择选项。
如何更改此代码以防止多次选择同一选项?
使用javascript
。 将change
事件处理程序附加到页面中的所有select
元素。 激活后,此事件会将所有列表设置为默认值,但更改的列表除外。
或者,它检查其他值是否与您选择的当前值相同,并警告用户。
或者,您可以在后端进行验证。 提交表单时,请检查是否有重复的值,并向用户抛出错误。
$(function() {
$("#first_stat").on("change", function() {
$("#second_stat").val("");
$("#third_stat").val("");
$("#fourth_stat").val("");
$("#fifth_stat").val("");
$("#sixth_stat").val("");
});
// Attach the event to the rest of them.
});
或第二种选择:
$(function() {
$("#first_stat").on("change", function() {
if ($("#second_stat").val() === $(this).val()) {
$(this).val("");
alert("Value is the same as Second Stat!")
}
// Go on
});
// Attach the event to the rest of them.
});
不漂亮,但有效。
对于第三个选项,您应该在Rails中查看自定义验证。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.