Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery's :checked not working?

So I'm trying to disable a text field if a checkbox isn't selected however its not working 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>

That is a short example of what I'm trying to do but it doesn't want to work. There are no errors in the console.

Could someone please explain why this isn't working?

like image 876
Spedwards Avatar asked Feb 07 '14 07:02

Spedwards


4 Answers

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

here's Fiddle

like image 137
Sergio Avatar answered Oct 16 '22 16:10

Sergio


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

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

Demo: Fiddle

like image 36
Arun P Johny Avatar answered Oct 16 '22 15:10

Arun P Johny


check this code..using this.checked

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

                if(this.checked)
                $('#colour').removeAttr('disabled');
                else 
                $('#colour').attr('disabled','disabled');

        });
like image 31
TKV Avatar answered Oct 16 '22 16:10

TKV


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

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

You can use checked property directly without condtion.

$('#check').change(function () {
    $('#colour').prop('disabled', !this.checked);
});
like image 41
Adil Avatar answered Oct 16 '22 15:10

Adil