在不同的类中独立限制各种复选框

Limit various checkbox inside different classes independently

本文关键字:复选框 独立      更新时间:2023-09-26

我是JS和jQuery的新手,我面临着一个我无法用我的知识解决的问题…我有一个网站,可以让用户选择不同种类的沙拉,但我需要限制一些项目的选择,我不知道该怎么做。复选框驻留在一个类中,但是我有太多的复选框,我只是想限制那些在特定类中的复选框。

$(document).ready(function(){
            $('#dressing-1 input[type=checkbox]').click(function(){
                if($('#dressing-1 input[type=checkbox]:checked').length>=2){
                    alert($('#dressing-1 input[type=checkbox]:checked').length);
                    $('#dressing-1 input[type=checkbox]:not(:checked)').prop("disabled", true);
                } else {
                    $('#dressing-1 input[type=checkbox]').prop("disabled", false);
                }
            });
    });

这是我现在拥有的代码,它正在工作,但只是对于第一个项目。我想使此代码可用于类.contenido-dressign的所有项目,现在我使用id #dressing-1只是为了证实它运行良好。我们的想法是编写一个更优雅的代码,而不是使用#dressing-1 #dressing-2。等等……这就是为什么我试图将此应用于容器.contenido-dressing

网址:lunchtime.cl/menu

函数中的this点击引用复选框本身,所以它不调用所有的复选框。像这样做:

$(document).ready(function(){
    $('.contenido-dressing').find(':checkbox').change(function(){
        var parent = $(this).parent()
        if(parent.find(':checked').length >= 2){
            parent.find(':checkbox:not(:checked)').attr('disabled', true);
        } else {
            parent.find(':checkbox').attr('disabled', false );
        }
    });
});

不需要每个函数,你绑定所有的复选框谁到div .contenigo-dressing和找到他的父。

Here a fiddle: http://jsfiddle.net/SyZ9Z/

"this"是一个对象,不是字符串

使用类似

的内容
$('[type=checkbox]', this)

如果复选框未被单击,则标签为。

我的建议:

$(document).ready(function(){
    $('.contenido-dressing').each(function(){
        var $c;
        $c = $('[type=checkbox]', this);
        $c.change(function(){
            if($c.filter(":checked").size() >= 2){
                $c.filter(":not(:checked)").attr('disabled', true);
            } else {
                $c.attr('disabled', false);
            }
        });
    });
});

更新:更短:

$(document).ready(function(){
    $('.contenido-dressing').each(function(){
        var $c;
        $c = $('[type=checkbox]', this);
        $c.change(function(){
            $c.filter(":not(:checked)")
              .attr('disabled', ($c.filter(":checked").size() >= 2));
        });
    });
});