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

我们两清 提交于 2019-12-22 06:46:56

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/6303443/grouping-checkboxes-and-allow-checking-a-maximum-of-three-in-each-group

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!