0

Hello: i have problem whit the checkbox ,i tried to make a button when it's checked its enable otherwise it's disable but it's not worked well, when i chekcked it enable but when i unchecked that it show the button enable .looking forward for yours help.

$(document).ready(function(){    
    $('#agree').change(function(){
       state = $('#agree').attr('value');
       if ( state == 'on'){
          $('#continue').removeAttr('disabled');
       }else if (state == '') {
          $('#continue').attr('disabled','disabled');
       }
    });
});
Hunter Turner
  • 6,804
  • 11
  • 41
  • 56
clift
  • 1
  • 1

3 Answers3

1

You are testing the checkbox's value to determine its state. However, its value does not change (natively) when checked or unchecked. I suggest referencing JavaScript's checked property, instead. See the list of properties at HTML Input Element.

In the example below, I'm using this.checked to reference the status of the checkbox that has triggered the "change" event. I'm also using a ternary operator to set the button's disabled property accordingly.

jQuery('#agree').change(function() {
  jQuery('#continue').prop('disabled', this.checked ? false : true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input type="checkbox" id="agree" />Click To Enable</label>
<button id="continue" type="button" disabled="disabled">A Button</button>
showdev
  • 28,454
  • 37
  • 55
  • 73
  • Thank you it's worked but i swap the place of true and false , Thank you very much for your Help. – clift Feb 07 '16 at 09:17
  • Oh, yes I see in your question you wanted the button enabled when the checkbox is checked. I updated my code for consistency. – showdev Feb 08 '16 at 17:41
0

After getting positive answer from you all i did it and now it works well .

 $('#agree').change(function() {

 $('#cont').prop('disabled', this.checked ? false : true);
 });  //this is the css code and the html code is in down 

  <!DOCTYPE html >
  <html lang = "en">
  <head> <meta charset = "utf-8">
    <title> removeAttr</title>
    </head>
 <body> 

 <p ><input id = "agree" type = "checkbox">I Agree</p><br>
 <input type = "submit" value = "Continue" id = "continue" disabled ="disabled">      

  <script type="text/javascript " src = "JQ.js"></script>
 <script type="text/javascript" src = "removeattr.js"></script> 
  </body>
 </html>
clift
  • 1
  • 1
-1

I think you better use toggleClass instead.

$('input').on('change',function(){
  $('button').toggleClass('disabled');
});
$('button.disabled').on('click',function(e){
  e.preventDefault();
});
devolk
  • 1