作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在这里搜索了其他类似的问题并尝试复制它们,但我不确定我做错了什么。
我只想选中一个复选框。我使用 limitCal
设置限制并检查 sibling 。
有人看到我做错了什么吗?
jQuery.fn.fadeBoolToggle = function (bool) {
return bool ? this.fadeIn(400) : this.fadeOut(400);
}
function packageSelect() {
var limitCal = 1;
$('.calendar-check').on('change', function () {
$(this).parents('.product-wrap:first').find('.checkmark-img').fadeBoolToggle(this.checked);
if ($(this).siblings(':checked').length >= limitCal) {
this.checked = false;
}
$('#next1').fadeBoolToggle($('.product-check:checked').length > 0);
var prods = [];
$('.calendar-check:checked').each(function () { prods.push($(this).val()) });
});
};
packageSelect();
.calendar-check {
display: none;
}
.product-wrap {
width: 100%;
position: relative;
display: block;
}
.checkmark-img {
display: none;
width: 40%;
height: auto;
z-index: 1;
cursor: pointer;
}
.package-check-toggle {
position: relative;
height: 100%;
width: 100%;
display: block;
}
.package-setup {
display: none;
margin: 40px 0;
width: 100%;
}
#calendar-box-wrap {
margin: 20px 0;
}
.calendar-box {
display: inline-block;
vertical-align: top;
width: 25%;
margin: 0 4%;
position: relative;
}
.calendar-selection-img {
width: 100%;
height: auto;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="calendar-box">
<div class="product-wrap">
<label for="cal-2year" class="package-check-toggle">
<img src="images/calendar-package.png" alt="2-year Photo Gift" class="calendar-selection-img">
<img src="images/checkmark-circle.png" class="checkmark-img total-center">
</label>
<input type="checkbox" class="calendar-check" id="cal-2year" value="2-year Calendar">
</div>
</div><div class="calendar-box">
<div class="product-wrap">
<label for="cal-whiteboard" class="package-check-toggle">
<img src="images/calendar-package.png" alt="Whiteboard Photo Gift" class="calendar-selection-img">
<img src="images/checkmark-circle.png" class="checkmark-img total-center">
</label>
<input type="checkbox" class="calendar-check" id="cal-whiteboard" value="Whiteboard Calendar">
</div>
</div>
最佳答案
这是您尝试执行的操作的简化版本。基本上,拦截复选框的点击事件可以防止默认操作(选中复选框)。 this
的 checked
值将是点击成功时的值。因此,如果未选中该复选框,则让点击发生。如果选中的复选框数量小于或等于限制,也让点击发生。否则,停止选中复选框。我将此示例的限制设置为 2 只是为了演示。
var limit = 2;
$('input:checkbox').on('click', function (e) {
if (!this.checked || $('input:checkbox:checked').length <= limit) {
return true;
}
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
关于javascript - 设置可以选择的复选框的数量限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42030675/
我是一名优秀的程序员,十分优秀!