分组复选框,并且允许在每个组中最多检查三个 [英] grouping checkboxes and allow checking a maximum of three in each group

查看:138
本文介绍了分组复选框,并且允许在每个组中最多检查三个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个应用程序,用户可以输入任意个人的数据。每个人最多可以选择六个选项中的三个。

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.

这里是一个示例代码

<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>

订阅者最多可以运行20次,如subscriber_1,subscriber_2,... subscriber_20。非常感谢您的协助。

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

推荐答案

,以便更容易附加事件处理程序:

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>

并使用此jQuery:

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

说明:在这些复选框的更改事件中,我们查找具有类 .subscriber 。我们得到这个div里面的复选框。如果有超过3(当前检查的计数也一样),我们取消选中当前的一个。

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')...

这称为属性从选择器开始

这篇关于分组复选框,并且允许在每个组中最多检查三个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆