To set a checkbox as checked or unchecked using jQuery, use the .prop()
method. Here’s how:
1. Check the Checkbox
Set the checked
property to true
:
javascript
// For a checkbox with ID "myCheckbox"
$('#myCheckbox').prop('checked', true);
2. Uncheck the Checkbox
Set the checked
property to false
:
javascript
$('#myCheckbox').prop('checked', false);
3. Toggle Checkbox State
Switch between checked/unchecked states:
javascript
// Toggle based on current state
$('#myCheckbox').prop('checked', function(_, currentVal) {
return !currentVal; // Inverts the current value
});
Example: Check/Uncheck Programmatically
html
<input type="checkbox" id="agreeCheckbox"> I agree
<button id="checkBtn">Check</button>
<button id="uncheckBtn">Uncheck</button>
javascript
// Check the checkbox
$('#checkBtn').click(function() {
$('#agreeCheckbox').prop('checked', true);
});
// Uncheck the checkbox
$('#uncheckBtn').click(function() {
$('#agreeCheckbox').prop('checked', false);
});
For Multiple Checkboxes
Check/uncheck all checkboxes with a shared class (e.g., selectAll
):
html
<input type="checkbox" class="item"> Item 1
<input type="checkbox" class="item"> Item 2
<button id="checkAll">Check All</button>
javascript
$('#checkAll').click(function() {
$('.item').prop('checked', true); // Check all
});
Alternative: Using .attr()
While .prop()
is preferred, .attr()
can work for older jQuery versions (but not recommended for dynamic states):
javascript
// Check
$('#myCheckbox').attr('checked', 'checked');
// Uncheck
$('#myCheckbox').removeAttr('checked');
Key Notes
.prop()
vs.attr()
:- Use
.prop()
to manipulate the current state (e.g.,true
/false
). - Avoid
.attr()
for dynamic states—it only affects the HTML attribute, not the live property.
- Use
- Pure JavaScript Alternative:javascriptCopyDownloaddocument.getElementById(‘myCheckbox’).checked = true;
When to Use?
- Use
.prop('checked', true/false)
for most cases. - Use
.attr()
only if you’re forced to support legacy code.