To get the value attribute of a checked checkbox in vanilla JavaScript, query for :checked on matching checkbox inputs (such as document.querySelector('input[type="checkbox"]:checked') for the first checked box or Array.from(document.querySelectorAll('input[type="checkbox"]:checked')).map(el => el.value) for all checked boxes) and read .value; in jQuery, use $('input[type="checkbox"]:checked').val() for the first checked checkbox or .map((_, el) => $(el).val()).get() to collect all checked values into a standard array. Both approaches return strings (defaulting to "on" in HTML if a checkbox omits an explicit value attribute) and should guard against empty/unmatched selections.
1. Getting Checked Checkbox Values in Vanilla JavaScript
Use document.querySelector() when you expect a single checked checkbox, or document.querySelectorAll() when a group can have multiple boxes checked at once:
// Return the .value of the first checked checkbox matching selector, or null if none checked
function getFirstCheckedValue(selector = 'input[type="checkbox"]') {
if (typeof selector !== "string" || selector.trim().length === 0) {
throw new TypeError("Expected selector to be a non-empty string.");
}
const checkedInput = document.querySelector(`${selector}:checked`);
if (!(checkedInput instanceof HTMLInputElement)) {
return null;
}
return checkedInput.value;
}
// Return a new array of .value strings for all checked checkboxes matching selector
function getAllCheckedValues(selector = 'input[type="checkbox"]') {
if (typeof selector !== "string" || selector.trim().length === 0) {
throw new TypeError("Expected selector to be a non-empty string.");
}
const checkedInputs = document.querySelectorAll(`${selector}:checked`);
return Array.from(checkedInputs)
.filter((el) => el instanceof HTMLInputElement)
.map((el) => el.value);
}
// Example usage (in a browser):
// console.log(getFirstCheckedValue('[name="permissions"]')); // e.g. "read" or null
// console.log(getAllCheckedValues('[name="permissions"]')); // e.g. ["read", "write"]
- First vs. all checked boxes:
querySelector(...:checked)stops at the first checked match, whereasquerySelectorAll(...:checked)gathers every checked box in document order. - Default
"on"value: If an<input type="checkbox">has novalue="..."attribute in HTML,.valuedefaults to"on".
2. Getting Checked Checkbox Values in jQuery
In jQuery, .val() called on a :checked checkbox collection returns the value of the first checked element (or undefined if none are checked), while .map(...).get() extracts every checked checkbox’s value cleanly:
// Return first checked checkbox value in jQuery, or fallback when none are checked
function getFirstCheckedValueJq($checkboxes, fallback = null) {
if (!($checkboxes && $checkboxes.length > 0)) {
return fallback;
}
const $checked = $checkboxes.filter('input[type="checkbox"]:checked').first();
if ($checked.length === 0) {
return fallback;
}
return $checked.val();
}
// Return a standard array of all checked checkbox values in jQuery
function getAllCheckedValuesJq($checkboxes) {
if (!($checkboxes && $checkboxes.length > 0)) {
return [];
}
return $checkboxes
.filter('input[type="checkbox"]:checked')
.map((_, el) => $(el).val())
.get();
}
// Example usage (in a browser with jQuery):
// const $perms = $('input[type="checkbox"][name="permissions"]');
// console.log(getFirstCheckedValueJq($perms)); // "read" or null
// console.log(getAllCheckedValuesJq($perms)); // ["read", "write"]
.get()converts a jQuery object into a native Array: Calling.map(...)alone returns a jQuery collection, so chain.get()when passing the result to standard array methods.- Scope selectors to a form or container: Pass a scoped selector or collection (like
$form.find('input[type="checkbox"]')) instead of a broad global query when multiple forms exist.
3. Reading During "change" Events and Handling Edge Cases
When reacting to user toggles, read checked values inside a "change" listener and keep in mind that .value is always a string even when you store numeric or boolean IDs:
// Non-mutating helper to parse checked values as numbers or keep strings
function parseCheckedNumbers(values) {
if (!Array.isArray(values)) {
return [];
}
return values
.map((v) => Number(v))
.filter((num) => !Number.isNaN(num));
}
// Example usage:
console.log(parseCheckedNumbers(["10", "25", "invalid"])); // [10, 25]
- Checkboxes vs. radio buttons: Both use
:checked, but checkboxes can have multiple simultaneous selections while radio groups with the samenametypically allow one. - Guard against
null/undefined: Always check whether any box is checked before calling methods like.trim()orNumber(...)on the result.
TL;DR: In vanilla JS, use document.querySelector('input[type="checkbox"]:checked')?.value (first) or Array.from(document.querySelectorAll('input[type="checkbox"]:checked'), el => el.value) (all); in jQuery, use $('input[type="checkbox"]:checked').val() (first) or $('input[type="checkbox"]:checked').map((_, el) => $(el).val()).get() (all).
