I have an HTML form with a set of checkboxes, how to make the user can only check a fixed number of them
Using div, the limit for the check box selection has been set to 1, so you can select maximum of only one check box. You can always update the limit in the source code.
Tip: You can only add one checkbox or option button at a time. To speed things up, after you add your first control, right-click it and select Copy > Paste. To edit or remove the default text for a control, click the control, and then update the text as needed.
The checked attribute is a boolean attribute. When present, it specifies that an <input> element should be pre-selected (checked) when the page loads. The checked attribute can be used with <input type="checkbox"> and <input type="radio"> . The checked attribute can also be set after the page load, with a JavaScript.
This example will count the number of checked inputs after each one is checked and compare against the maximum number allowed. If the maximum is exceeded, the remaining checkboxes are disabled.
jQuery(function(){
var max = 3;
var checkboxes = $('input[type="checkbox"]');
checkboxes.change(function(){
var current = checkboxes.filter(':checked').length;
checkboxes.filter(':not(:checked)').prop('disabled', current >= max);
});
});
Here is a working example - http://jsfiddle.net/jaredhoyt/Ghtbu/1/
This binds to each checkbox a bit of logic that checks to see how many checkboxes are checked in the current form. If that number equals 2, we disable all other boxes.
$("form").on("click", ":checkbox", function(event){
$(":checkbox:not(:checked)", this.form).prop("disabled", function(){
return $(this.form).find(":checkbox:checked").length == 2;
});
});
This works on a per-form basis, meaning you can have multiple forms that don't touch the inputs of one another. In the demo below I showcase three forms, all of which contain three checkboxes. The restriction of 2 checkboxes is limited to their respective forms.
Demo: http://jsbin.com/epanex/4/edit
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With