How to limit the number of selected checkboxes?

JqueryFormsCheckbox

Jquery Problem Overview


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?

Jquery Solutions


Solution 1 - Jquery

Using change event you can do something like this:

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

See this working demo

Solution 2 - Jquery

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

Solution 3 - Jquery

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!');
     }
  });
});

Solution 4 - Jquery

I think we should use click instead change

Working DEMO

Solution 5 - Jquery

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

i used this.

Solution 6 - Jquery

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

Solution 7 - Jquery

Working DEMO

Try this

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

Solution 8 - Jquery

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;
    	}
    });

Solution 9 - Jquery

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 );
  });
});

Solution 10 - Jquery

I have Alter this function to auto uncheck previous

      var limit = 3;
      $('.compare_items').on('click', function(evt) {
        index = $(this).parent('td').parent('tr').index();
        if ($('.compare_items:checked').length >= limit) {
          $('.compare_items').eq(localStorage.getItem('last-checked-item')).removeAttr('checked');
          //this.checked = false;
        }
        localStorage.setItem('last-checked-item', index);
      });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="compare_items">1
<input type="checkbox" class="compare_items">2
<input type="checkbox" class="compare_items">3
<input type="checkbox" class="compare_items">4
<input type="checkbox" class="compare_items">5
<input type="checkbox" class="compare_items">6
<input type="checkbox" class="compare_items">7
<input type="checkbox" class="compare_items">8
<input type="checkbox" class="compare_items">9
<input type="checkbox" class="compare_items">10

Solution 11 - Jquery

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);
		}
	});

Solution 12 - Jquery

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()
   }
}

Solution 13 - Jquery

This function simply checks if you have just checked a checkbox. If yes, it increments the checked value by one. If it reaches the limit then the next checkbox is rejected.

var limit = 3;
var checked = 0;
$('.single-checkbox').on('change', function() {
  if($(this).is(':checked'))
    checked = checked+1;

  if($(this).is(':checked') == false)
    checked = checked-1;

  if(checked > limit) {
    this.checked = false;
    checked = limit;
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>

Solution 14 - Jquery

This method works well with checkboxes in a container, such as bootstrap checkbox

    const checkedLimmit = 2;

    function ValidateCheckBoxGroup(container) {

        if (container.find('input[type="checkbox"]:checked').length >= checkedLimmit) {
            container.find('input[type="checkbox"]:not(:checked)').prop('disabled', true);
            container.find('input[type="checkbox"]:not(:checked)').closest('div.checkbox').addClass('disabled');
        } else {
            container.find('input[type="checkbox"]:not(:checked)').prop('disabled', false);
            container.find('input[type="checkbox"]:not(:checked)').closest('div.checkbox').removeClass('disabled');
        }
    }

    $(function () {
        // validate containers on page load
        $('div.checkbox-group').each(function () {
            ValidateCheckBoxGroup($(this));
        });

        // set checkbox events
        $('div.checkbox-group input[type="checkbox"]').change(function () {
            ValidateCheckBoxGroup($(this).closest("div.checkbox-group"));
        });
    });

Solution 15 - Jquery

(function ($) {
  $(document).ready(function () {
    $(document).on("change", ".pricing-levels-3 input", function () {
      var numberOfChecked = $(".pricing-levels-3 input:checkbox:checked").length;
      if (numberOfChecked >= 2) {
        $(".pricing-levels-3 input:not(:checked)").prop("disabled", true);
      } else {
        $(".pricing-levels-3 input:not(:checked)").removeAttr("disabled", true);
      }
    });
  });
})(jQuery);

Solution 16 - Jquery

This is working for me with checkbox name.

<script>
    // limit checkbox select
    $('input[name=vehicle]').on('change', function (e) {
    if ($('input[name=vehicle]:checked').length > 3) {
        $(this).prop('checked', false);
        alert("allowed only 3");
    }
});
</script>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionalexchencoView Question on Stackoverflow
Solution 1 - JqueryletiagoalvesView Answer on Stackoverflow
Solution 2 - JqueryPraveenView Answer on Stackoverflow
Solution 3 - JquerycoderView Answer on Stackoverflow
Solution 4 - JqueryHammad HassanView Answer on Stackoverflow
Solution 5 - JqueryJinhyeok LeeView Answer on Stackoverflow
Solution 6 - JqueryentropView Answer on Stackoverflow
Solution 7 - JquerySarathSprakashView Answer on Stackoverflow
Solution 8 - JquerybzimView Answer on Stackoverflow
Solution 9 - JqueryBobzView Answer on Stackoverflow
Solution 10 - JqueryVaimeoView Answer on Stackoverflow
Solution 11 - JqueryPurple TentacleView Answer on Stackoverflow
Solution 12 - JqueryDennis Dae OhView Answer on Stackoverflow
Solution 13 - JqueryMr. CryptoView Answer on Stackoverflow
Solution 14 - JqueryMrCADmanView Answer on Stackoverflow
Solution 15 - JqueryNoruzzamanView Answer on Stackoverflow
Solution 16 - JqueryMYNUL HASANView Answer on Stackoverflow