How to disable checkboxes after limited checkboxes are checked? I want to create two different forms where in first form user can check only 3 checkboxes and remaining checkboxes should be disabled and in the second form only two checkboxes can be selected and remaining should go disable.
Asked
Active
Viewed 514 times
0
-
5have you tried anything? could you please tell us where exactly you are struggling? – Sandeep Kushwah Sep 18 '15 at 18:46
-
http://stackoverflow.com/questions/2330209/jquery-checkbox-enable-disable check it – m2j Sep 18 '15 at 18:47
-
1@priya : I hope your problem has been fixed, please mark the answer whichever answer helped you. So that, it can help others. – Sandeep Kushwah Sep 18 '15 at 19:38
2 Answers
2
Here's a simple snippet that should do what you want. Just adjust the custom attribute data-checksallowed
on your form and it should handle any number of allowed checkboxes.
$('[data-checksallowed]').on("change", 'input[type="checkbox"]', function() {
var parent = $(this).closest("[data-checksallowed]");
var checksallowed = parent.data('checksallowed');
var checkboxes = parent.find('input[type="checkbox"]');
var checkedboxes = checkboxes.filter(':checked');
var uncheckedboxes = checkboxes.not(checkedboxes);
if (checkedboxes.length == checksallowed)
uncheckedboxes.prop('disabled', true);
else
uncheckedboxes.prop('disabled', false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form data-checksallowed="3">
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
</form>
<form data-checksallowed="2">
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
</form>

Dave
- 10,748
- 3
- 43
- 54
-
@priya why did you unaccept this answer? Is something not working for you? – Dave Sep 19 '15 at 18:03
1
Something like this will work for you.
<div id="chks">
<input type="checkbox" value="1" /> 1
<input type="checkbox" value="2" /> 2
<input type="checkbox" value="3" /> 3
<input type="checkbox" value="4" /> 4
<input type="checkbox" value="5" /> 5
<input type="checkbox" value="6" /> 6
<input type="checkbox" value="7" /> 7
<input type="checkbox" value="8" /> 8
</div>
The javascript will look like this:
$('#chks input[type="checkbox"]').click(function(){
// get the count of all checked boxes
var cnt = $('#chks input[type="checkbox"]:checked').length;
if(cnt == 3){
// if cnt is equal to 3 disable all checkboxes that are NOT checked
// you want to leave the checked ones enabled
$('#chks input[type="checkbox"]').not(':checked').attr('disabled', 'disabled');
}else{
// if count is not equal to 3 make sure the unchecked are enabled
// count should never be more than 3 because this will disable them
$('#chks input[type="checkbox"]').not(':checked').removeAttr('disabled');
}
});

Gregg Duncan
- 2,635
- 1
- 14
- 20