Lennart Kloppenburg Lennart Kloppenburg - 4 months ago 29
jQuery Question

Enable/disable submit button when any/no checkbox in form is checked

I am trying to use jQuery to dynamically enable/disable a submit button for a form.

The HTML:

<form id="user-add-to-group">
<table class="group-list">
<tbody>
<tr>
<th>Voornaam</th>
<th>Achternaam</th>
<th>S/P-nummer</th>
<th>Email</th>
<th>Type</th>
</tr>
<tr>
<td>Name</td>
<td>Surname</td>
<td>No.</td>
<td>email@bs.com</td>
<td>student</td>
<td><input type="checkbox" name="user_add_to_group[]" value="75F0CE8F-4B6F-4E17-BC7B-0B06AAD84625"></td>
</tr>
</tbody>
</table>
<button disabled="disabled" type="button" id="participant_add_btn" name="participant_add_btn" class="btn btn-primary">Add</button>
</form>


And the jQuery:

$('table.group-list tr').on("click", function(){
$(this).find("input[type=checkbox]").trigger('click');
if($("#user-add-to-group input[type=checkbox]:checked").length>0){
$("#participant_add_btn").prop("disabled","false");
}
else {
$("#participant_add_btn").prop("disabled","disabled");
}
});


I want to make the entire table row clickable, so the jQuery triggers a click event when the tr is clicked. This works, but I cannot seem to figure out why my button won't be enabled afterwards. I want to enable it when any checkbox within the form is checked, and disable it when none of them are.

If more info is needed, please let me know.

Answer

jQuery.prop expects value to be Boolean, any string which is not empty is considred as true as it is truthy value

$('table.group-list tr').on("click", function() {
  $(this).find("input[type=checkbox]").trigger('click');
  $("#participant_add_btn").prop("disabled", !$("#user-add-to-group input[type=checkbox]:checked").length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="user-add-to-group">
  <table class="group-list">
    <tbody>
      <tr>
        <th>Voornaam</th>
        <th>Achternaam</th>
        <th>S/P-nummer</th>
        <th>Email</th>
        <th>Type</th>
      </tr>
      <tr>
        <td>Name</td>
        <td>Surname</td>
        <td>No.</td>
        <td>email@bs.com</td>
        <td>student</td>
        <td>
          <input type="checkbox" name="user_add_to_group[]" value="75F0CE8F-4B6F-4E17-BC7B-0B06AAD84625">
        </td>
      </tr>
    </tbody>
  </table>
  <button disabled="disabled" type="button" id="participant_add_btn" name="participant_add_btn" class="btn btn-primary">Add</button>
</form>

Comments