0

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?

1 Answers1

0

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);
});
Community
  • 1
  • 1
dave
  • 62,300
  • 5
  • 72
  • 93
  • I knew it had to be something simple and silly I was missing. Thanks –  Mar 27 '14 at 17:31