[jquery] How to limit the number of selected checkboxes?

I have the following HTML:

<div class="pricing-levels-3">
  <p><strong>Which level would you like? (Select 3 Levels)</strong></p>
  <input class="single-checkbox"type="checkbox" name="vehicle" value="Bike">Level 1<br>
  <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 2<br>
  <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 3<br>
  <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 4<br>
  <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 5<br>
  <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 6<br>
  <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 7<br>
</div>

Live site:

http://www.chineselearnonline.com/amember/signup20.php

How can I do it so that the user can only select 3 of those checkboxes?

This question is related to jquery

The answer is


I think we should use click instead change

Working DEMO


Working DEMO

Try this

var theCheckboxes = $(".pricing-levels-3 input[type='checkbox']");
theCheckboxes.click(function()
{
    if (theCheckboxes.filter(":checked").length > 3)
        $(this).removeAttr("checked");
});

This is how I made it work:

// Function to check and disable checkbox
function limit_checked( element, size ) {
  var bol = $( element + ':checked').length >= size;
  $(element).not(':checked').attr('disabled',bol);
}

// List of checkbox groups to check
var check_elements = [
  { id: '.group1 input[type=checkbox]', size: 2 },
  { id: '.group2 input[type=checkbox]', size: 3 },
];

// Run function for each group in list
$(check_elements).each( function(index, element) {
  // Limit checked on window load
  $(window).load( function() {
    limit_checked( element.id, element.size );
  })

  // Limit checked on click
  $(element.id).click(function() {
    limit_checked( element.id, element.size );
  });
});

I did this today, the difference being I wanted to uncheck the oldest checkbox instead of stopping the user from checking a new one:

    let maxCheckedArray = [];
    let assessmentOptions = jQuery('.checkbox-fields').find('input[type="checkbox"]');
    assessmentOptions.on('change', function() {
        let checked = jQuery(this).prop('checked');
        if(checked) {
            maxCheckedArray.push(jQuery(this));
        }
        if(maxCheckedArray.length >= 3) {
            let old_item = maxCheckedArray.shift();
            old_item.prop('checked', false);
        }
    });

$("input:checkbox").click(function(){
    if ($("input:checkbox:checked").length > 3){
      return false;
   }
});

I'd say like letiagoalves said, but you might have more than one checkbox question in your form, so I'd recommend to do like this:

  var limit = 3;
    $('input.single-checkbox').on('change', function(evt) {
        if($('input.single-checkbox').siblings('input.single-checkbox:checked').length > limit) {
            this.checked = false;
        }
    });

$('.checkbox').click(function(){
  if ($('.checkbox:checked').length >= 3) {
    $(".checkbox").not(":checked").attr("disabled",true);
  }
  else 
    $(".checkbox").not(":checked").removeAttr('disabled');
});

i used this.


Try like this.

On change event,

$('input[type=checkbox]').on('change', function (e) {
    if ($('input[type=checkbox]:checked').length > 3) {
        $(this).prop('checked', false);
        alert("allowed only 3");
    }
});

Check this in JSFiddle


Try this DEMO:

 $(document).ready(function () {
   $("input[name='vehicle']").change(function () {
      var maxAllowed = 3;
      var cnt = $("input[name='vehicle']:checked").length;
      if (cnt > maxAllowed) 
      {
         $(this).prop("checked", "");
         alert('Select maximum ' + maxAllowed + ' Levels!');
     }
  });
});

I have Alter this function to auto uncheck previous

_x000D_
_x000D_
      var limit = 3;_x000D_
      $('.compare_items').on('click', function(evt) {_x000D_
        index = $(this).parent('td').parent('tr').index();_x000D_
        if ($('.compare_items:checked').length >= limit) {_x000D_
          $('.compare_items').eq(localStorage.getItem('last-checked-item')).removeAttr('checked');_x000D_
          //this.checked = false;_x000D_
        }_x000D_
        localStorage.setItem('last-checked-item', index);_x000D_
      });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="checkbox" class="compare_items">1_x000D_
<input type="checkbox" class="compare_items">2_x000D_
<input type="checkbox" class="compare_items">3_x000D_
<input type="checkbox" class="compare_items">4_x000D_
<input type="checkbox" class="compare_items">5_x000D_
<input type="checkbox" class="compare_items">6_x000D_
<input type="checkbox" class="compare_items">7_x000D_
<input type="checkbox" class="compare_items">8_x000D_
<input type="checkbox" class="compare_items">9_x000D_
<input type="checkbox" class="compare_items">10
_x000D_
_x000D_
_x000D_


If you want to uncheck the checkbox that you have selected first under the condition of 3 checkboxes allowed. With vanilla javascript; you need to assign onclick = "checking(this)" in your html input checkbox

var queue = [];
function checking(id){
   queue.push(id)
   if (queue.length===3){
    queue[0].checked = false
    queue.shift()
   }
}