I'm trying to limit the number of two different types of checkboxes checked at the same time. I want to create a specific combination of boxes checked and then fire an alert, three yellow ones and two red. My problem is that the alert only fires on only one of the statements and not on both. I can check only two red but as many yellow as I want.
$('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.");
}
});
Try this. I believe this is what you are looking for.
You want to be able to click no more than 2 red and 3 yellow and at the same time, you want to show an alert if there are 2 reds and 3 yellows clicked
$('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"/>