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

Change function with checkboxes and multiple selectors

本文关键字:选择器 功能 复选框      更新时间:2023-09-26

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

$('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"/>