【发布时间】:2014-03-27 17:22:07
【问题描述】:
我在标签中有一组复选框,就像这样
<div class="constraints">
<label>
<label>
<input type="checkbox" ...>
</label>
.
.
.
<label>
<input type="checkbox" ...>
</label>
</label>
.
.
.
<label>
<label>
<input type="checkbox" ...>
</label>
.
.
.
<label>
<input type="checkbox" ...>
</label>
</label>
</div>
在每组标签 (.constraints > label) 中,必须至少选中一个复选框。为了确保这一点,我编写了这个 jQuery 代码,如果所有这些都未选中,则应该简单地勾选组中的第一个框。
$('form .constraints input').on('change', function() {
var checks = $(this).closest('.constraints > label').find('input') ;
var atleastone = false ;
checks.each(function() {
if ($(this).is(':checked')) {
atleastone = true ;
}
}) ;
if (!atleastone) {
checks.first().attr('checked', true) ;
}
}) ;
只工作一次。我第一次选中或取消选中 任何 个框时,脚本可以工作,但任何后续调用都不会产生任何结果。
出了什么问题?
【问题讨论】:
标签: javascript jquery forms checkbox