There are two issues with the code:
var x = $(this).attr('value');
will always return the value of the checkbox, whether it's checked or not. I fyou want to check its checked state, it's the checked
property on the element (this.checked
in your handler, or $(this).prop("checked")
if you want more jQuery).
$('#myButton').attr('disabled');
is a no-op: It reads the value of the attribute, and then throws it away. To set it, you'd do $('#myButton').attr('disabled', 'disabled');
Note that using prop('disabled', trueOrFalse)
is the preferred way to set/clear the disabled state.
$('#myCheckBox').on('change', function() {
$("#myButton").prop('disabled', !this.checked);
});
But since you specifically said you wanted to use the attribute:
$(document).ready(function() {
$('#myCheckBox').on('change', function() {
if (this.checked) {
$('#myButton').removeAttr('disabled');
} else {
$('#myButton').attr('disabled', 'disabled');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="myCheckBox">
I agree with terms and conditions
<input type="checkbox" id="myCheckBox" />
</label>
<br />
<br />
<input type="button" id="myButton" value="Submit" disabled />
But here's an example of using the property, which is really the way to go:
$(document).ready(function() {
$('#myCheckBox').on('change', function() {
$('#myButton').prop('disabled', !this.checked);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="myCheckBox">
I agree with terms and conditions
<input type="checkbox" id="myCheckBox" />
</label>
<br />
<br />
<input type="button" id="myButton" value="Submit" disabled />