我已经尝试了几种方法来禁用Django ModelForm中的复选框。使用Jquery,我可以编写一些代码,在选中某个数字时禁用复选框,但它也会禁用已选中的复选框。我想要一种动态的方式来复选和取消复选框,只有当达到限制时还没有被选中的块框。
这是我的JS:
function checkBoxes() {
$(' input[type=checkbox]').
attr('disabled', true);
$(document).on('click',
'input[type=checkbox]',
function (event) {
if ($(this).is(":checked")) {
console.log("1")
} else {
console.log('2')
}
});
}我试图弄清楚的问题是,由于我使用Django创建复选框列表的方式,如何验证该框是否已被选中:
<div style="height:30px"></div>
<form method="post">
{% csrf_token %}
{{ context.form.as_p }}
<button type="submit">Submit</button>
</form>

如何修复我的JS,并能够动态地启用和禁用复选框,即当达到限制时,禁用所有未选中的复选框,当限制降低时,允许再次单击复选框?
发布于 2021-08-18 15:34:16
只需在jquery选择器中使用:checked和:not(:checked),如下所示:
$(document).on('click', 'input[type=checkbox]', function(event) {
if ($('.checkbox-container input[type=checkbox]:checked').length >= 3) {
$('.checkbox-container input[type=checkbox]:not(:checked)').attr('disabled', true);
} else($('.checkbox-container input[type=checkbox]').attr('disabled', false));
});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<div class="checkbox-container">
<input type="checkbox" id="scales1" name="scales1" checked>
<input type="checkbox" id="scales2" name="scales2" checked>
<input type="checkbox" id="scales3" name="scales3">
<input type="checkbox" id="horns1" name="horns1">
<input type="checkbox" id="horns2" name="horns2">
<input type="checkbox" id="horns3" name="horns3">
</div>
</body>
</html>
https://stackoverflow.com/questions/68834877
复制相似问题