Skip to content

How to properly use Jquery to disable checkboxes in a Django Form when a certain number of them are checked

I’ve been trying a couple of ways to disable checkboxes in a Django ModelForm. Using Jquery I was able to write some code that does disable checkboxes when a certain number is checked, but it also disables the ones that have been checked. I want a dynamic way to check and uncheck boxes and only block boxes that have not been checked when the limit is hit.

This is my 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')
                }
            });
  }

The issue I’m having trying to figure this out is how to verify if the box has been checked or not because of how I’m creating the checkbox list with Django:

<div style="height:30px"></div>
<form method="post">
    {% csrf_token %}
    {{ context.form.as_p }}
    <button type="submit">Submit</button>
</form>

enter image description here

How can I fix my JS and be able to enable and disable checkboxes dynamically, meaning when the limit is hit, disable all the unchecked boxes, and when the limit is reduced allow checkboxes to be clicked again?

Answer

Just use :checked and :not(:checked) in your jquery selector, like this:

$(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>