Question
How can I determine whether a checkbox is checked in jQuery when I know its id? The following function always appears to return the number of checked checkboxes regardless of the supplied ID:
function isCheckedById(id) {
alert(id);
var checked = $("input[@id=" + id + "]:checked").length;
alert(checked);
if (checked == 0) {
return false;
} else {
return true;
}
}
Short Answer
You will learn how jQuery selects a checkbox by ID, how the :checked selector works, and why .is(":checked") is usually the clearest way to return a Boolean value.
Concept
A checkbox has a checked state: it is either checked or unchecked. In jQuery, the :checked selector matches checked checkboxes and selected radio buttons.
When you already know the checkbox's unique id, select that one element first, then test its state:
$("#newsletter").is(":checked");
This returns true when the checkbox is checked and false otherwise.
The original selector uses [@id=...]. The @ syntax was used by very old jQuery versions and is not valid in modern jQuery. Use an ID selector such as #idValue, or a standard attribute selector such as [id="idValue"].
Checking state matters because a checkbox's HTML markup and its current browser state can differ. The current state is represented by the checked property, which jQuery's :checked selector reads.
Mental Model
Think of a checkbox as a light switch with a unique label.
- The checkbox
idis the label, such asnewsletter. - Selecting
#newslettermeans finding that specific switch. - Asking
.is(":checked")means asking, “Is this switch currently on?”
Do not count every lit switch in the room when you only need to know whether one labelled switch is on.
Syntax and Examples
Select a checkbox with its ID and test it with .is(":checked"):
function isCheckedById(id) {
return $("#" + id).is(":checked");
}
Example HTML:
<label>
<input id="email-updates" type="checkbox" checked>
Receive email updates
</label>
Example use:
const receivesUpdates = isCheckedById("email-updates");
console.log(receivesUpdates); // true
You can also read the DOM property directly through jQuery:
const isChecked = $("#email-updates").prop("checked");
Both approaches return a Boolean for a matching checkbox. reads naturally when you are testing a condition.
Step by Step Execution
Consider this page:
<input id="terms" type="checkbox">
And this JavaScript:
function isCheckedById(id) {
return $("#" + id).is(":checked");
}
const acceptedTerms = isCheckedById("terms");
console.log(acceptedTerms);
Execution steps:
isCheckedById("terms")receives the string"terms"."#" + idcreates the selector"#terms".$("#terms")finds the element whose ID isterms..is(":checked")tests whether that element is currently checked.- Because the example checkbox has no
checkedstate, the method returns .
Real World Use Cases
Checkbox state checks are common in browser-based applications:
- Terms acceptance: prevent form submission until a user accepts required terms.
- Notification settings: save whether email or SMS notifications are enabled.
- Bulk actions: enable a Delete button only when at least one table row is selected.
- Optional form sections: show delivery instructions only when “Use a different delivery address” is checked.
- Filters: include products marked “In stock” or “On sale” when a filter checkbox is enabled.
For one known checkbox, use its ID and .is(":checked"). For a group of checkboxes, select the group and use .length to count checked items.
Real Codebase Usage
In real projects, developers usually check a checkbox at the moment it affects an action, rather than storing a separate variable that can become outdated.
Form validation with a guard clause
$("#signup-form").on("submit", function (event) {
if (!$("#terms").is(":checked")) {
event.preventDefault();
$("#terms-error").text("You must accept the terms before continuing.");
return;
}
});
The early return keeps the valid path simple.
Reacting when the user changes a setting
$("#email-updates").on("change", function () {
const enabled = $(this).is(":checked");
console.log("Email updates enabled:", enabled);
});
Inside an event handler, this is the checkbox that triggered the event. Using avoids looking it up again by ID.
Common Mistakes
Using obsolete @id syntax
This is not modern jQuery selector syntax:
$("input[@id=" + id + "]:checked")
Use an ID selector instead:
$("#" + id).is(":checked")
Forgetting to quote attribute selector values
If you need an attribute selector, quote its value:
$("input[id='email-updates']:checked")
For a dynamic ID that may contain selector characters, prefer $.escapeSelector:
$("#" + $.escapeSelector(id)).is(":checked");
Counting when a Boolean is needed
This works, but it is unnecessarily indirect for one checkbox:
const checked = $("#terms:checked").length;
return checked > 0;
Comparisons
| Task | Recommended jQuery code | Result |
|---|---|---|
| Check one checkbox by ID | $("#terms").is(":checked") | true or false |
| Read one checkbox property | $("#terms").prop("checked") | true or false |
| Count checked items in a group | $("input[name='topics']:checked").length | Number |
| Find every checked checkbox | $("input[type='checkbox']:checked") | jQuery collection |
| Read initial HTML attribute | $("#terms").attr("checked") |
Cheat Sheet
// Is one checkbox checked?
$("#checkbox-id").is(":checked");
// Read the current checked property
$("#checkbox-id").prop("checked");
// Set the current checked property
$("#checkbox-id").prop("checked", true);
$("#checkbox-id").prop("checked", false);
// Count checked checkboxes in a named group
$("input[name='group-name']:checked").length;
// Handle user changes
$("#checkbox-id").on("change", function () {
console.log($(this).is(":checked"));
});
Rules:
- Use unique IDs for individual elements.
- Use
:checkedfor the current checked state. - Use
.is()or.prop()when you needtrueor .
FAQ
How do I check whether a checkbox is checked in jQuery?
Use:
$("#my-checkbox").is(":checked");
It returns true or false.
Does :checked work for radio buttons too?
Yes. :checked matches checked checkboxes and the selected radio button.
Why does .length return 1 or 0?
.length counts the number of elements in a jQuery collection. A unique checkbox selector can match one element (1) or no checked elements (0). It is not itself a Boolean.
Should I use .attr("checked") or .prop("checked")?
Use .prop("checked") for the current user-visible state. The checked attribute is mainly the initial HTML default.
Mini Project
Description
Build a small newsletter preferences form. The form has one required consent checkbox and optional notification settings. It demonstrates checking a single checkbox by ID, responding to changes, and preventing an invalid form submission.
Goal
Prevent submission until the user accepts the required terms, while displaying the current state of the optional email setting.
Requirements
<|DELIM_lmsR2|>
Keep learning
Related questions
Abort Ajax Requests with jQuery jqXHR.abort()
Learn how to cancel an in-progress jQuery Ajax request with jqXHR.abort(), handle abort status safely, and avoid stale UI updates.
Access the Correct this Inside a JavaScript Callback
Learn why JavaScript this changes in callbacks and how to preserve an object context using bind, arrow functions, and event handler patterns.
Add Key-Value Pairs to JavaScript Objects
Learn how to add key-value pairs to JavaScript objects with dot and bracket notation, dynamic keys, examples, and common mistakes.