I've got a set of checkboxes in labels, like so
<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>
Within each group of labels (.constraints > label
) at least one checkbox must be checked. To ensure this, I wrote this jQuery code, which should simply tick off the first box in the group if all of them are unchecked.
$('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) ;
}
}) ;
Which works exactly once. The first time I check or uncheck any of the boxes, the script works, but any subsequent calls result in nothing.
What is going wrong?