我的html模板中有两个复选框表单,其中一个允许多个选项,另一个只允许选中一个选项。
我试图限制第一个复选框形式,只允许2个框,但目前的代码影响两个复选框形式。
我不能使用id或名称,因为这些是由DB, id_something1, id_something2等生成的。人们过去是如何处理这个问题的?
当前JS
<script>
$('input[type=checkbox]').on('change', function (e) {
if ($('input[type=checkbox]:checked').length > 2)) {
$(this).prop('checked', false);
}
});
</script>
我试图将表单限制为2个复选框
<li class="list-group-item">
<div class="custom-control custom-checkbox">
<label>Test</label></label><input type="checkbox" name="orange" id="id_orange" checked>
</div>
</li>
<li class="list-group-item">
<div class="custom-control custom-checkbox">
<label>Test2</label><input type="checkbox" name="banana" id="id_banana" checked>
</div>
</li>
第二种形式也受到影响
<ul id="id_someform">
<li>
<label for="id_someform_1"></label><input type="checkbox name="someForm" value=1" id="id_someform_1"
</li>
<li>
<label for="id_someform_2"></label><input type="checkbox name="someForm" value=2" id="id_someform_2"
</li>
</ul>
将内部选择器的范围限制在周围的形式:
$('input[type=checkbox]').change(function() {
const form = $(this).closest('form');
if ( form.find('input[type=checkbox]:checked').length > 2) ) {
$(this).prop('checked', false);
}
});
注意,我已经用jQuery的change()
方法简化了你的语法。
<script>
$('input[type=checkbox]').on('change', function (e) {
if ($('input[type=checkbox]:checked').length > 2)) {
$(this).prop('checked', false);
}
});
</script>
上面的代码片段将监听所有的复选框事件,相反,在你的复选框上使用不同的id属性,并改变选择器来使用你想要监听事件的复选框的id,例如
<script>
$('input#id_orange').on('change', function (e) {
if ($('input[type=checkbox]:checked').length > 2)) {
$(this).prop('checked', false);
}
});
</script>
如果表单不同,您可以尝试替换以下行:
$('input[type=checkbox]').on('change', function (e) {
:
$('#form-id input[type=checkbox]').on('change', function (e) {
或:
$('form.class input[type=checkbox]').on('change', function (e) {
或任何其他不同于另一种形式的父元素
例如:
$('#form-id input[type=checkbox]').on('change', function (e) {
if ( $('#form-id input[type=checkbox]:checked').length > 2 ) {
$(this).prop('checked', false);
}
});
我已经测试过了,它对我有效。