我试图创建一个包含下拉列表的表单,每个下拉列表都使用相同的选项;但我希望每个选项只选择一次。我怎样才能做到这一点?
以下是我想要的表单的一般代码:
<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 -->
显然,这并不能防止多次选择选项。
如何更改此代码以防止多次选择相同的选项?
答案 0 :(得分:0)
使用.wide-div {
position: absolute;
left: 0;
right: 0;
}
。将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.
});
不漂亮但有效。
对于第三个选项,您应该在Rails中查看自定义验证。