Reputation: 4492
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?
Upvotes: 12
Views: 31538
Reputation: 2663
check this code..using this.checked
$('#check').change(function(){
if(this.checked)
$('#colour').removeAttr('disabled');
else
$('#colour').attr('disabled','disabled');
});
Upvotes: 1
Reputation: 2595
Here you go:
<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>
Upvotes: 1
Reputation: 3096
use this.checked
$('#check').change(function(){
if(this.checked){
$('#colour').removeAttr('disabled');
} else {
$('#colour').attr('disabled',true);
}
});
Upvotes: 1
Reputation: 38102
Try this:
$('#check').change(function(){
if($('#check').is(':checked')){
$('#colour').removeAttr('disabled');
} else {
$('#colour').attr('disabled','');
}
}).change();
In order to make your jsFiddle working, you need to:
1) Include jQuery library
2) Use is(':checked')
to check whether checkbox is checked or not.
3) Trigger change()
event on page load to catch the default checked status.
Upvotes: 1
Reputation: 388316
Use .prop() also use the checked state to set the value
$('#check').change(function () {
$('#colour').prop('disabled', !this.checked);
});
Demo: Fiddle
Upvotes: 10
Reputation: 148120
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);
});
Upvotes: 1