Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grouping checkboxes and allow checking a maximum of three in each group

I would like to have an application where a user will enter data for arbitrary individuals. each individual will have a choice of a maximum of three of six options. I want help on how to force a maximum of three choices using jquery on any indivual.

here is a sample code

<div id="subscriber_1">
   <input type=checkbox name=national>
   <input type=checkbox name=international>
   <input type=checkbox name=business>
   <input type=checkbox name=entertainment>
   <input type=checkbox name=religion>
   <input type=checkbox name=sports>
</div>

the subscribers can run upto 20, like subscriber_1, subscriber_2, ... subscriber_20. I will be grateful for your assistance.

like image 974
Tamseyc Avatar asked Jun 10 '11 07:06

Tamseyc


People also ask

How do I group a checkbox?

To group checkboxes, click and drag the selection box around the checkboxes you'd like to group and then click Group checkboxes in the right sidebar. F. Label the fields - Note, labeling checkboxes helps to set up conditional logic for the checkboxes.

How do I select one checkbox from multiple checkboxes in HTML?

change(function() { $("#myform input:checkbox"). attr("checked", false); $(this). attr("checked", true); }); This should work for any number of checkboxes in the form.

How do I allow only one checkbox to be checked?

If you want to allow the user to check only one checkbox from a group of the checkboxes, it can be done easily using jQuery. At first, include the jQuery library. To modify the default functionality of checkboxes and use like the radio buttons, you need to restrict the user to select multiple checkboxes.

How do you validate that at least one checkbox is checked?

There is a form with multiple checkboxes and we're going to make sure that at least one is checked using pure JavaScript. To set a custom validation error message, we will use setCustomValidity() method.


1 Answers

You should add a class to your subscriber divs, to make it easier to attach event handlers:

<div id="subscriber_1" class="subscriber">...</div>
<div id="subscriber_2" class="subscriber">...</div>

And use this jQuery:

$('.subscriber :checkbox').change(function () {
    var $cs = $(this).closest('.subscriber').find(':checkbox:checked');
    if ($cs.length > 3) {
        this.checked = false;
    }
});

jsFiddle Demo

Explanation: On the change event of these checkboxes, we look for the closest parent that has the class .subscriber. We get the checked checkboxes inside this div. If there are more than 3 (the currently checked one counts as well), we uncheck the current one.


If you certainly don't want to add classes, you can use this selector instead:

$('[id^="subscriber_"] :checkbox')...

This is called the Attribute Starts With Selector.

like image 183
kapa Avatar answered Nov 15 '22 03:11

kapa