【发布时间】:2013-11-13 02:00:52
【问题描述】:
我在一个表单上有很多复选框。我需要将总数限制为三个复选框,仅此而已。我有有效的代码,但我刚刚将我的表单升级到 Foundation Custom Forms,我的脚本不再工作,我无法让它工作。
如何重新编写脚本才能工作?
这是当前脚本:
$(function(){
var max = 3;
var checkboxes = $('input[type="checkbox"]');
checkboxes.click(function(){
var $this = $(this);
var set = $this.add($this.prevUntil('label')).add($this.nextUntil('label'));
var current = set.filter(':checked').length;
return current <= max;
});
});
表格代码如下:
<label>Effects <span class="red">required</span></label>
<label for="CAT_Custom_365571_0"><input type="checkbox" value="Creative" id="CAT_Custom_365571_0" name="CAT_Custom_365571" style="display: none;">
<span class="custom checkbox"></span> Creative</label>
<label for="CAT_Custom_365571_1"><input type="checkbox" value="Euphoric" id="CAT_Custom_365571_1" name="CAT_Custom_365571" style="display: none;">
<span class="custom checkbox"></span> Euphoric</label>
<label for="CAT_Custom_365571_2"><input type="checkbox" value="Uplifted" id="CAT_Custom_365571_2" name="CAT_Custom_365571" style="display: none;">
<span class="custom checkbox"></span> Uplifted</label>
<label for="CAT_Custom_365571_3"><input type="checkbox" value="Energetic" id="CAT_Custom_365571_3" name="CAT_Custom_365571" style="display: none;">
<span class="custom checkbox"></span> Energetic</label>
<label for="CAT_Custom_365571_4"><input type="checkbox" value="Lazy" id="CAT_Custom_365571_4" name="CAT_Custom_365571" style="display: none;">
<span class="custom checkbox"></span> Lazy</label>
<label for="CAT_Custom_365571_5"><input type="checkbox" value="Focused" id="CAT_Custom_365571_5" name="CAT_Custom_365571" style="display: none;">
<span class="custom checkbox"></span> Focused</label>
<!-- MORE CHECKBOXES -->
显然,当我更改表单时,我破坏了脚本。我该如何解决这个问题?
【问题讨论】:
-
您只需要找出点击事件中选择了多少。基本上你必须使用相对于复选框不同的选择器。抓住单击复选框的父级,然后是兄弟级,然后是这些兄弟级的子级,以计算有多少被选中。
-
如果它们在单个元素中(比如
id='foo'),你可以这样做:document.querySelectorAll('#foo input[type="checkbox"]:checked').length > 3,你就完成了。在 jQuery 中可能是$('#foo input[type="checkbox"]:checked').length > 3。如果选中的数量超过 3 个,则显示一条消息,以便用户修复它。 -
如果复选框没有被用户实际点击,而是一个设置状态的脚本,那么你就无能为力了,因为不会触发复选框上的
click函数
标签: javascript jquery forms checkbox zurb-foundation