Paul S
Paul S

Reputation: 89

One checkbox of many should always stay unchecked

There are a lot of topics about JavaScript and conditional checking checkboxes, but I have not found one that matches my case.

My use case: I have generated a number of rows with checkboxes each row, let's say the number is n. Now the user should be able to check only n-1 of them. So in other words when we have 4 checkboxes and 3 of 4 are checked, the last one should be disabled. When only 2 of 4 are checked then all checkboxes are available.

I have tried:

var $checks = $('input:checkbox').click(function (e) {
        var numChecked = $checks.filter(':checked').length;
        var lastUnchecked = $checks.prop('checked', false);

        if (numChecked = $checks.length - 1) {
            lastUnchecked.disabled = true;
        }
        else {
            //enable checkbox that was disabled before
            lastUnchecked.disabled = false;
        }
    });

But this doesn't work because var lastUnchecked = $checks.prop('checked', false); return all checkboxes, not only unchecked

Upvotes: 0

Views: 157

Answers (3)

Dominique Fortin
Dominique Fortin

Reputation: 2238

This is simpler

$(document).ready(function(){
  var numBox;

  var $checks = $('input:checkbox').click(function (e) {
      var numChecked = $checks.filter(':checked').length;

      if (numChecked < numBox - 1) {
        $checks.filter(':disabled').prop('disabled', false);
      } else {
        $checks.not(':checked').prop('disabled', true);
      }
  });

  numBox = $check.length;
});

Upvotes: 0

Mitya
Mitya

Reputation: 34556

Try this.

Logic: on change, first re/enable all checkboxes. Then figure out afresh if we need to disable any, based on how many are checked.

var table = $('table'), cbs = $(':checkbox');
table.on('change', ':checkbox', function(evt) {
    cbs.prop('disabled', false);
    if (cbs.filter(':checked').length == cbs.length - 1) 
        cbs.not(':checked').prop('disabled', 1);
})

Fiddle.

Upvotes: 1

kapantzak
kapantzak

Reputation: 11750

Try counting the checked items each time user checkes one of them:

$(document).on('change', '.chk', function() {
  var that = $(this);
  var par = that.closest('ul');
  var max = par.find('.chk').length - 1;
  var checked = par.find('.chk').filter(':checked').length;
  if (checked < max) {
    par.find('.chk').prop('disabled', '');
  } else {
    par.find('.chk').not(':checked').prop('disabled', 'disabled');
  }               
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<ul>
  <li><input class="chk" type="checkbox" /> Checkbox</li>  
  <li><input class="chk" type="checkbox" /> Checkbox</li>  
  <li><input class="chk" type="checkbox" /> Checkbox</li>  
  <li><input class="chk" type="checkbox" /> Checkbox</li>  
  <li><input class="chk" type="checkbox" /> Checkbox</li>  
</ul>

Upvotes: 1

Related Questions