简体   繁体   中英

Checking at least one checkbox within groups of checkboxes

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?

You need to change every place you have

.attr('checked')
.attr('checked', true)

to

.prop('checked')
.prop('checked', true)

To see why, you can check .prop() vs .attr()

You could shorten your code a lot by doing

$('form .constraints input').on('change', function() {
  var checks = $(this).closest('.constraints > label').find('input');
  var checked = checks.filter(':checked').length == 0;
  if (checked) checks.first().prop('checked', checked);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM