title: Stop checking checkboxes after a number of checkboxes have been checked in jQuery or JavaScript
body: <p>I want to stop the user to check another checkbox after a certain number of checkboxes have been checked already. i.e. After 3 checkboxes are checked, the user cannot check anymore and a message says 'You're not allowed to choose more than 3 boxes.'</p>
  
  <p>I'm almost there but the last checkbox is still being checked and I don't want that, I want it to be unchecked with the message appearing.</p>
  
  <p>How do I do that:</p>
  
  <pre><code>var productList = $('.prod-list'),
      checkBox = productList.find('input[type="checkbox"]'),
      compareList = $('.compare-list ul');
  
  productList.delegate('input[type="checkbox"]', 'click', function () {
    var thisElem = $(this),
        thisData = thisElem.data('compare'),
        thisImg = thisElem.closest('li').find('img'),
        thisImgSrc = thisImg.attr('src'),
        thisImgAlt = thisImg.attr('alt');
  
    if (thisElem.is(':checked')) {
      if ($('input:checked').length &lt; 4) {
  
          compareList.append('&lt;li data-comparing="' + thisData + '"&gt;&lt;img src="' + thisImgSrc + '" alt="'+ thisImgAlt +'" /&gt;&lt;li&gt;');
  
      } else {
          $('input:checked').eq(2).attr('checked', false);
          alert('You\'re not allowed to choose more than 3 boxes');
      }
    } else {
      var compareListItem = compareList.find('li');
  
      for (var i = 0, max = compareListItem.length; i &lt; max; i++) {
          var thisCompItem = $(compareListItem[i]),
              comparingData = thisCompItem.data('comparing');
  
          if (thisData === comparingData) {
              thisCompItem.remove();
          }
      }
  
    }
  
  });
  </code></pre>