javascript - 使用复选框和多个选择器更改功能

标签 javascript jquery checkbox statements

我试图限制同时选中的两种不同类型的复选框的数量。我想创建一个特定的选中框组合,然后触发警报,三个黄色和两个红色。我的问题是,警报仅针对其中一项陈述触发,而不针对两项陈述触发。 我只能检查两个红色,但可以检查任意数量的黄色。

$('input[name=redChoice], input[name=yellowChoice]').change(function() {

    var cntRed = $('input[name=redChoice]:checked').length;
    var cntYellow = $('input[name=yellowChoice]:checked').length;

    var maxRedAllowed2 = 2;
    var maxYellowAllowed3 = 3;

    if (cntRed > maxRedAllowed2 && cntYellow > maxYellowAllowed3) {
        $(this).prop('checked', false);
        alert("Du har valt 3 stycken gula och 2 stycken röda."); 
    }
});

最佳答案

试试这个。我相信这就是您正在寻找的。

您希望能够点击不超过 2 个红色和 3 个黄色,同时您希望在点击 2 个红色和 3 个黄色时显示警报

$('input[name=redChoice], input[name=yellowChoice]').change(function() {

    var cntRed = $('input[name=redChoice]:checked').length;
    var cntYellow = $('input[name=yellowChoice]:checked').length;

    var maxRedAllowed2 = 2;
    var maxYellowAllowed3 = 3;

    
    
     if (cntRed == maxRedAllowed2 && cntYellow == maxYellowAllowed3) {
        //$(this).prop('checked', false);
        alert("Du har valt 3 stycken gula och 2 stycken röda."); 
    }
    else if (cntRed > maxRedAllowed2){
       $(this).prop('checked', false);
    }
    else if (cntYellow > maxYellowAllowed3){
       $(this).prop('checked', false);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
red<input type="checkbox" name="redChoice"/>
red<input type="checkbox" name="redChoice"/>
red<input type="checkbox" name="redChoice"/>
red<input type="checkbox" name="redChoice"/>
yellow<input type="checkbox" name="yellowChoice"/>
yellow<input type="checkbox" name="yellowChoice"/>
yellow<input type="checkbox" name="yellowChoice"/>
yellow<input type="checkbox" name="yellowChoice"/>
yellow<input type="checkbox" name="yellowChoice"/>

关于javascript - 使用复选框和多个选择器更改功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33144078/

相关文章:

javascript - Chrome 开发工具中的 console.log 对象/函数属性

javascript - 如果不添加附件,PouchDB 代码将无法工作

javascript - CKEditor - 未捕获的类型错误 : Cannot read property 'clearCustomData' of null in Chrome

javascript - 验证 ExtJS CheckboxGroup 复选框

屏幕旋转后立即调用 Android Checkbox 监听器方法

javascript - 检查所有复选框

javascript - 多个html页面应用程序cordova中的http请求处理

php - 我需要一种方法来自动调整 iframe 的大小,无论我查到什么或其他任何地方,它都无法正常工作

php - 在Resize上设置最大高度

c# - 转换没有时区的 JSON 日期