checkbox returns "on" value after it is unchecked
I'm following a tutorial where you make a checkbox that enables a disabled button and when you uncheck the box, the button becomes disabled again. The problem is that when I uncheck the box, it seems like the checkbox still in an "on" state because the button is not disabled. The code works in Chrome but not in Firefox 3.6.
Here is my code:
<p><input type="checkbox" id="agree" >I agree</p>
<input id="continue" type="button" value="continue" disabled='true'>
<script>
$('#agree').change(function(){
var state = $(this).attr('value');
if(state == 'on'){
$('#continue').removeAttr('disabled');
}else if(state == ''){
开发者_JS百科 $('#continue').attr('disabled', 'false');
}
});
</script>
a checkbox's check value doesn't change with .val()
you should be using .is('checked')
like so:
$('#agree').change(function() {
var state = $(this).is(':checked'); //state = true/false depending on state
if (state) { //if true
$('#continue').removeAttr('disabled'); //remove disabled
} else { //else (false)
$('#continue').attr('disabled', 'disabled'); //add disabled (you shouldn't set it to 'false' as it WILL be disabled and it'll confuse you.
}
});
Here's an Example to see my points.
Try :
$(function() {
$('#agree').click(function() {
if ($(this).is(':checked')) $('#continue').attr('disabled', false);
else $('#continue').attr('disabled', true);
});
});
LINK : http://jsfiddle.net/Mmm4h/
Try this:
$('#agree').change(function() {
if($("#agree").is(":checked"))
$('#continue').removeAttr('disabled');
else
$('#continue').attr('disabled', false);
});
http://jsfiddle.net/TGQZs/1/
精彩评论