Write jQuery code to enable the submit button only when a checkbox is checked
Description: The “Register” button must be disabled at the start, and enabled only when “I agree” is checked.
Hint:
- Use
.prop('disabled', ...)in thechangeevent of the checkbox.
HTML of the page
<label><input type="checkbox" id="agree"> I agree to the terms</label>
<button id="register" disabled>Register</button>
Solution
$('#agree').on('change', function () {
$('#register').prop('disabled', !this.checked);
});
console.log('start: disabled = ' + $('#register').prop('disabled'));
$('#agree').prop('checked', true).trigger('change');
console.log('checked: disabled = ' + $('#register').prop('disabled'));
$('#agree').prop('checked', false).trigger('change');
console.log('unchecked: disabled = ' + $('#register').prop('disabled'));
Console output
start: disabled = true
checked: disabled = false
unchecked: disabled = true
How it works
this.checkedis true or false. We setdisabledto the opposite.
Read Set Content (prop).
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |