JQuery: checked not working?

Therefore, I am trying to disable the text box if the checkbox is not selected, but it does not work as it should.

Example: http://jsfiddle.net/GV7U9/

<input type="checkbox" id="check" checked /><br /> #<input type="text" size="8" maxlength="6" id="colour" placeholder="ffffff" /> <script> $('#check').change(function(){ if( $('#check:checked') ){ $('#colour').removeAttr('disabled'); } else { $('#colour').attr('disabled',''); } }); </script> 

This is a brief example of what I'm trying to do, but it does not want to work. There are no errors in the console.

Can someone explain why this is not working?

+7
javascript jquery
source share
7 answers

Use .prop (), also use checked state to set value

 $('#check').change(function () { $('#colour').prop('disabled', !this.checked); }); 

Demo: Fiddle

+6
source share

try $('#check').is(':checked')

here is fiddle

+4
source share

Use length to find out if the element is checked, otherwise your condition will be true always. When the length is longer, condition 0 will be true and false otherwise.

  if( $('#check:checked').length ){ $('#colour').removeAttr('disabled'); } else { $('#colour').attr('disabled',''); } 

You can use the checked property directly without conditions.

 $('#check').change(function () { $('#colour').prop('disabled', !this.checked); }); 
+1
source share

Try the following:

 $('#check').change(function(){ if($('#check').is(':checked')){ $('#colour').removeAttr('disabled'); } else { $('#colour').attr('disabled',''); } }).change(); 

For your jsFiddle to work, you need to:

1) Enable jQuery library

2) Use is(':checked') to check if the checkbox is checked.

3) change() trigger event on the page to get checked status by default.

Demo Screenshot

+1
source share

use this.checked

 $('#check').change(function(){ if(this.checked){ $('#colour').removeAttr('disabled'); } else { $('#colour').attr('disabled',true); } }); 

Fiddle

+1
source share

Here you go:

http://jsfiddle.net/4dwkG/

 <input type="checkbox" id="check" checked /><br /> #<input type="text" size="8" maxlength="6" id="colour" placeholder="ffffff" /> <script> $('#check').change(function(){ if( $('#check').is(":checked") ){ $('#colour').removeAttr('disabled'); } else { $('#colour').attr('disabled',''); } }); </script> 
+1
source share

check this code .. using this.checked

  $('#check').change(function(){ if(this.checked) $('#colour').removeAttr('disabled'); else $('#colour').attr('disabled','disabled'); }); 
0
source share

All Articles