Let's talk now.
407-476-6930 / 850-366-8392 (PCB)

Limit Number of Checkboxes Selected

by Brandon Welch
Web Designer/Developer & Web Expert
Connect with me: | Facebook | LinkedIn

If you are using jQUERY, here is a simple code snippet to limit or set a max on the number of checkbox options a user can select.

How the Input should be setup:


<input type="checkbox" value="1" name="question[]"/>
<input type="checkbox" value="2" name="question[]"/>

How your Javascript should look:


$(document).ready(function() {
$('[name="question[]"]').click(function () {
selected = $('[name="question[]"]').filter(':checked').length;
if (selected > 9){
alert('You may select only 9 questions.');
$(this).attr('checked', false);
}
});
});

What this Code Does

This code checks inputs named “question[]” on each click and determines if there are more than 9 checked. If there are, it displays a simple alert with a message and unchecks the last input checked.