gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:37:47 27 4
gpt4 key购买 nike

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

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com