作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我试图限制同时选中的两种不同类型的复选框的数量。我想创建一个特定的选中框组合,然后触发警报,三个黄色和两个红色。我的问题是,警报仅针对其中一项陈述触发,而不针对两项陈述触发。我只能检查两个红色,但可以检查任意数量的黄色。
$('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/
我是一名优秀的程序员,十分优秀!