0

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.

Sandeep Kushwah
  • 590
  • 1
  • 18
  • 35
priya
  • 21
  • 2

2 Answers2

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
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