我正在尝试限制复选框
及其相关标签
可选择的最大数量。复选框工作正常,但标签的可选择范围仍然超过限制。
我的 html input
的格式如下:
<div data-toggle="buttons" class="btn-group bizmoduleselect">
<label id="b-<?php echo $term->term_id; ?>" class="btn btn-default <?php echo $labelchk ?>">
<div class="bizcontent">
<input id="youaresure" type="checkbox" name="email_cats[]" <?php echo $chk ?> value="<?php echo $term->term_id ?>" />
<h5><?php echo $term->name ?></h5>
</div>
</label>
</div>
我的 jQuery 来限制复选框和标签就像:
var $checkboxes = $('input[id="youaresure"]');
var $parent = $checkboxes.parent('label');
var max = 5;
$checkboxes.show();
$checkboxes.change(function () {
$(this).prop('checked', function () {
if ($(this).is(':checked')) {
return ($checkboxes.filter(':checked').length <= max) ? true : false;
}
});
});
$parent.show();
$parent.change(function () {
$(this).prop('class', function () {
if ($(this).is('active')) {
return ($parent.filter('active').length <= max) ? true : false;
}
}
基本上,php 会向 inputs:checked
的 labels
父级插入一个 active
类,我应该阻止这两个 labels
> 和如果超过 5 则选择输入
。
复选框很好,但父标签仍然可选,而且基本上是可见的。
编辑:我忘记指出它与 Bootstrap 一起使用,并且每个复选框都像按钮一样受到威胁!
最佳答案
没有change
事件于 <label>
。一切都应该在 <input>
的事件处理程序中完成
我的建议是当达到限制时禁用其他复选框。
以下将切换标签上的事件类以及禁用/启用未选中的输入
var max = 5;
var $checkboxes = $(':checkbox').change(function(e) {
var maxChecked = $checkboxes.filter(':checked').length === max;
// disable/enable others based on limit
$checkboxes.not(':checked').prop('disabled', maxChecked);
// toggle label active based on checked state
$(this).closest('label').toggleClass('active', this.checked);
});
关于javascript - jQuery - 将标签和复选框组限制为最大数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38672723/