selectedOptions Collects Multi Select Picks

Read chosen items from a multi-select through selectedOptions so form payloads keep every picked value without scanning all option elements.

JavascriptForm Validation

Code

javascriptsnippet
20 lines
const select = document.querySelector('#regions');
select.options[0].selected = true; // emea
select.options[2].selected = true; // apac

// selectedOptions is a live collection of picked <option> elements only.
const picked = [...select.selectedOptions].map((o) => o.value);
console.log('picked:', picked);

// value returns only the first selection — useless for multiple selects.
console.log('value says:', select.value);

// Deselecting through the collection is possible but the DOM is the
// source of truth: clear via the option's selected flag.
select.selectedOptions[0].selected = false;
console.log('after deselect:', [...select.selectedOptions].map((o) => o.value));

// Empty selection is an empty list, not null — safe to join directly.
select.options[0].selected = false;
select.options[2].selected = false;
console.log('payload:', select.selectedOptions.length === 0 ? [] : picked);

How the snippet works

Top-level bindings select, picked hold the demo state — nothing sits inside a function scope.

Points of care

  • The snippet leans on document — browser-only surfaces a bare Node process cannot provide.

Applying it

Look for the picked:, value says:, after deselect: prefixes when the file runs; they tie each line to its step.

Statements that matter

const picked = [...select.selectedOptions].map((o) => o.value);

Interactive Tools for This Topic

FAQ

Does selectedOptions Collects Multi Select Picks run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.