0
votes

I have a couple of checkboxes, of which some are already checked on page load.

What I want to do is disable the other checkboxes if 2 boxes are checked.

My code works fine if I check/uncheck boxes myself. But when 2 boxes are already checked (using javascript or HTML) on page load, the another box can still be checked until the boxes get disabled.

Since 2 boxes are already checked on page load, the other checkboxes should be disabled until I uncheck one of the 2 checked boxes. This is currently not the case.

This is my javascript:

jQuery(function($) {

 var max = 2;
 var checkboxes = $('input[type="checkbox"]');

  checkboxes.change(function(){
      var current = checkboxes.filter(':checked').length;
      checkboxes.filter(':not(:checked)').prop('disabled', current >= max);
  });

   $('.one').attr('checked','checked');
   $('.two').attr('checked','checked');

});

which goes below my checkboxes:

        <div id="checkboxes">
                <input type="checkbox" class="1" id="checkbox" name='Some[array]' value="1"> 
                <input type="checkbox" class="2" id="checkbox" name='Some[array]' value="2"> 
                <input type="checkbox" class="3" id="checkbox" name='Some[array]' value="3"> 
                <input type="checkbox" class="4" id="checkbox" name='Some[array]' value="4"> 
        </div>
2

2 Answers

2
votes

Just fire the .change() event when the page loads:

checkboxes.change(function () {
    var current = checkboxes.filter(':checked').length;
    checkboxes.filter(':not(:checked)').prop('disabled', current >= max);
}).change();

jsFiddle example

1
votes

Your selectors are wrong, and the checked event will not fire if you change the value programmatically. However, you can trigger the change event manually to force your code to work when you initially set the values. Use the two lines below:

$('.1').prop('checked','checked').change();
$('.2').prop('checked','checked').change();