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>