Reputation: 37
I have the following code for enabling the submit button after clicking the checkbox.
HTML:
<input type="checkbox" checked="checked" id="check"><a href="#">terms and conditions</a>
<input type="submit" name="submit" id="post" value="submit">
Script:
$('#check').click(function(){
if($(this).attr('checked') == false){
$('#post').attr("disabled","disabled");
}
else {
$('#post').removeAttr('disabled');
}
});
But this is not working in my localhost. The button is enabled all the time even if the checkbox is not selected. Please help me to make it work.
Upvotes: 0
Views: 992
Reputation: 147363
Lots of answers.
Don't call any form control "submit" as it will shadow the form's submit method (i.e. form.submit
will reference the control, not the method).
All you need is something like:
<form ...>
<input type="checkbox" onclick="this.form.submitButton.disabled = !this.checked" ...>
<input type="submit" name="submitButton" disabled>
</form>
Upvotes: 0
Reputation: 5545
Here is the filddle
Here is the javascript for working with it
$(function(){
$('#check').click(function(){
if($(this).attr('checked')!="checked"){
$("#post").attr("disabled","disabled");
} else {
$("#post").removeAttr("disabled");
}
});
});
Upvotes: 0
Reputation: 5340
$(this).attr('checked') will always true, it just read the "checked" attr value out,
use
this.checked
or
$(this).prop('checked')
See this: http://jsfiddle.net/m6aBZ/
Upvotes: 0
Reputation: 780779
$('#check').click(function() {
$('#post').prop('disabled', !$(this).is(':checked'));
}
.attr()
checks the attribute in the HTML, not the current state of the HTML; .is(':checked')
tests the latter. Also, I believe it's preferable to use .prop()
to change the disabled state of the element dynamically.
Upvotes: 1
Reputation: 3381
Use .is(':checked')
$('#check').click(function() {
if(!$(this).is(':checked')) {
$('#post').attr("disabled","disabled");
} else {
$('#post').removeAttr('disabled');
}
});
Upvotes: 0
Reputation: 4873
Does it disable it if you check, and then uncheck the checkbox? If so, then you just need to set disabled as the default state.
Upvotes: 0