2015-10-15 59 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