skip to Main Content

I need to toggle attribute ‘disable’ in button by checkbox selection? Please help

$(document).ready(function() {
  $("#checkbox").click(function() {
    $(".btn-submit").attr("checked");
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="checkbox" class="checkbox" id="checkbox">
<button class="btn-submit" disabled>Submit</button>

2

Answers


  1. You need to use something like the below:

    $("#checkbox").click(function() {
        if ($('#checkbox').prop("checked") == true) {
            $('.btn-submit').prop("disabled", false);
        } else {
            $('.btn-submit').prop("disabled", true);
        }
    });
    

    Line 2 will check to see if the box is checked. If it is, it will set the disabled property of the submit button to false. If it is unchecked, it will reverse the action and disable the button again.

    When enabling buttons which follow a set of steps, always ask yourself, is there any way an end user can get around this (in this instance, trying to uncheck the box)

    Hope this helps you

    Login or Signup to reply.
  2. You can use this.checked to determine if the checkbox being changed is ticked or not.

    You can then use .prop("disabled", disabled_true_false) to disable the button.

    Updated snippet to only enable the button once the tickbox has been ticked:

    $("#checkbox").change(function() {
      $(".btn-submit").prop("disabled", !this.checked);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <input type="checkbox" class="checkbox" id="checkbox">
    <button class="btn-submit" disabled>Submit</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search