Search code examples
javascripthtmljquerybuttondisable

disable button in jquery on checkbox


If a user checked on the checkbox then the button should be enabled. If not then button should be disabled.

function test(){
  if($(this).val() === true){      //not working
      $('#send_button').prop('disabled', false);
  } 
  else if($(this).val() === false){
      $('#send_button').prop('disabled', true);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>

<input id="ischeck" type="checkbox" name="ischeck" value=true>
<label for="ischeck">ischeck</label><br>        

<button id="send_button" class="btn btn-primary pull-right" onclick="test()">Send</button>


Solution

  • You should add an event listener on the input checkbox dom element in order to catch the value change like this (check the documentation here):

    $("#ischeck").change(...);
    

    Then, check which value the input has, and set the button disabled property accordingly:

     $('#send_button').prop('disabled', !this.checked);
    

    Note: Do not forget for the case of checkbox input type, in order to set the initial value, you should use the property checked like this (more info here):

    <input id="ischeck" type="checkbox" name="ischeck" checked=true>
    

    Follows a full working example:

    $("#ischeck").change(function () {
        // You want to se the property disable of the send button with the oposite value of the input;
        // Example: Input: true [then] Button disabled: false
        $('#send_button').prop('disabled', !this.checked);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
    
    <input id="ischeck" type="checkbox" name="ischeck" checked=true>
    <label for="ischeck">ischeck</label><br>        
    
    <button id="send_button" class="btn btn-primary pull-right" onclick="test()">Send</button>