javascript - 当检查一定数量时,如何正确使用jQuery以Django表格禁用复选框
问题描述
我一直在尝试几种方法来禁用 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 并能够动态启用和禁用复选框,这意味着当达到限制时,禁用所有未选中的框,当限制减少时允许再次单击复选框?
解决方案
只需
在您的 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>
推荐阅读
- groovy - JMETER - WebDriver Sampler - Groovy - 动态名称(3 级)
- reactjs - 如何在 Formik 中集成 TinyMCE 富文本编辑器?
- javascript - 如何使用反应挂钩有条件地重置状态计数
- php - 如何从表PHP的第一行循环多个变量
- azure-synapse - 无法捕获日志分析中的插入/更新/删除(使用突触专用 SQL POOL 审计数据)
- javascript - 在对象数组的数组中查找对象
- amazon-web-services - AWS Lambda 控制器路由不匹配,{proxy+} - 404 Not Found
- vba - VBScript:将文本文件读入另一个文件而不跳过最后一行
- r - 如何使用 R dplyr 找到行中第一个非零值的列索引?
- javascript - 输入字段的日期格式化程序,它以 MM/DD/YYYY 格式格式化给定的数字,它也接受 Angular 中的 NA 字母