首页 > 解决方案 > 当检查一定数量时,如何正确使用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 并能够动态启用和禁用复选框,这意味着当达到限制时,禁用所有未选中的框,当限制减少时允许再次单击复选框?

标签: javascriptjquerydjango

解决方案


只需 在您的 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>


推荐阅读