2015-10-15 41 views
0

我试图限制同时选中两个不同类型复选框的数量。我想创建一个特定的组合框检查,然后发出警报,三个黄色和两个红色。我的问题是,警报只会触发其中一个语句,而不会触发两个语句。 我可以检查只有两个红色,但我想要的黄色。使用复选框和多选择器更改函数

$('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."); 
    } 
}); 
+0

你可以发布你的HTML吗? –

+0

我认为你需要使用'||'而不是'&&' –

+0

也许使用'> ='而不是'>'。 – Scimonster

回答

1

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

你希望能够点击超过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"/>

以示警告
+0

这正是我想要的!非常感谢!对此,我真的非常感激! – Christine

+0

太好了!花了一段时间来理解你的问题。 –

+0

我很抱歉。我在这里的第一个问题,所以我不习惯制定这样的问题。但我得到了我想要的东西,所以这可能不会是我最后一次。 – Christine