[Answered ]-How to check and keep checkboxes checked when others are unchecked

1👍

You can use $("[name=marked_delete]").filter(':checked').length to get length of checked checkboxes and if length is > 0 simply show button else hide.

Demo Code :

$(document).ready(function() {
  $('#select-all').click(function() {
    var checked = this.checked;
    $('input[type="checkbox"]').each(function() {
      this.checked = checked;
    });
  })
});
$('input[type="checkbox"]').click(function() {
  //filter total checked checkboxes.. or use input[type="checkbox"] as selector..
  if ($("[name=marked_delete]").filter(':checked').length > 0) {
    $('#delete_all').prop("hidden", false);
  } else {
    $('#delete_all').prop("hidden", true);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" action="{% url 'delete_students' %}">

  <table class="layout container">
    <thead>
      <th><input type="checkbox" id="select-all"></th>
    </thead>
    <tbody>
      <tr>
        <td>
          <input type="checkbox" name="marked_delete" value="{{ student.pk }}">
        </td>
      </tr>
      <tr>
        <td>
          <input type="checkbox" name="marked_delete" value="{{ student.pk }}">
        </td>
      </tr>
      <tr>
        <td>
          <input type="checkbox" name="marked_delete" value="{{ student.pk }}">
        </td>
      </tr>
    </tbody>
  </table>

  <button class="btn btn-dark" id="delete_all" hidden="hidden">Delete Selected</button>
</form>
👤Swati

Leave a comment