Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit checked checkbox in a form

I have an HTML form with a set of checkboxes, how to make the user can only check a fixed number of them

like image 921
Ahmed Waheed Avatar asked May 05 '12 04:05

Ahmed Waheed


People also ask

How do I limit the number of checkboxes selected in JavaScript?

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.

How many check boxes can be selected at a time?

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.

How do I make a checkbox always checked?

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.


2 Answers

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/

like image 102
jaredhoyt Avatar answered Oct 06 '22 23:10

jaredhoyt


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

like image 45
Sampson Avatar answered Oct 06 '22 23:10

Sampson