My form elements are generated by Rails.
<input id="agree_to_rules" name="agree_to_rules" type="checkbox" value="1">
I’m trying this to set the state of the submit button on the form, based on whether the checkbox is checked or not. (I know inline css is not greate, I’m just trying to get a visual cue while I test.
<script>
$(function() {
if ($('#agree_to_rules').is(':checked')) {
$('#tweet_your_entry').attr('disabled', 'false').css({color: '#666666'});
} else {
$('#tweet_your_entry').attr('disabled', 'true').css({color: '#f5f5f5'});
}
});
</script>
It just seems to always evaluate to false, no matter the state of the checkbox. Anyone spot the error? Or can point me to a cleaner way to achieve the same result — I’m very new to JS and jQuery.
UPDATE
Here’s what I’m using now, based on the answer below:
<script>
$(function() {
$('#agree_to_rules').change(function() {
if ( $('#agree_to_rules').prop("checked") ) {
$('#tweet_your_entry').attr('disabled', 'false').removeClass('ui-button-disabled ui-state-disabled');
} else {
$('#tweet_your_entry').attr('disabled', 'true').addClass('ui-button-disabled ui-state-disabled');
}
});
});
</script>
The trouble is, when the button is active, after someone’s checked the box, the jquery-ui hover state for the button doesn’t kick in any more. Anyone know why?
You need to place your code in a handler like
.change(), and pass booleantrue/falseinstead of strings.Working example: http://jsfiddle.net/CPFns/
Now the code will run each time the checkbox changes.
If you only wanted it to run when the page loads, then get rid of the change handler, but again be sure to pass
trueandfalseinstead of"true"and"false".Here’s a more concise way to write it.
Working example: http://jsfiddle.net/CPFns/1/
EDIT:
Based on the fiddle provided, I think this is a little cleaner solution:
Example: http://jsfiddle.net/psBQ7/2/
It seems that there’s some issue with
jQueryUI, where itshoverfunctionality will never be enabled if the button wasdisabledwhen the page loads.I removed the
disabled="disabled"from the HTML, and simply triggered the.change()on page load, which will see that the box isn’t checked, therefore disabling the button after jQueryUI has been applied.