select Element Reads Selected Options

Read a select through value, selectedIndex, options, and selectedOptions; programmatic value assignment fires change just like user selection.

TypescriptForm Validation

Code

typescriptsnippet
22 lines
const select = document.querySelector<HTMLSelectElement>("#env");
if (!select) throw new Error("select markup missing");

function describeSelection(): string {
  // value 总是字符串;selectedIndex 指向 options 里的位置
  const option = select.options[select.selectedIndex];
  return `${select.value} @ index ${select.selectedIndex} (${option?.text ?? "none"})`;
}

console.log(describeSelection());

select.addEventListener("change", () => {
  console.log(describeSelection());
  // selectedOptions 处理 multiple 场景:单选时长度恒为 1
  const chosen = [...select.selectedOptions].map((option) => option.value);
  console.log(`selected: ${chosen.join(",")}`);
});

// 程序化切换与手动选择走同一条 change 路径
select.value = "staging";
select.dispatchEvent(new Event("change"));

What the snippet does

The load-bearing code sits in the function describeSelection — everything else is wiring.

The failure path is explicit — Error is raised when the guard condition holds.

Points of care

  • Built-in APIs only, so there is no supply chain to vet.
  • document.querySelector, HTMLSelectElement and dispatchEvent are browser-only surfaces — run this in a page, not a bare Node process.
  • The guard !select short-circuits the flow with an early throw when its condition holds.

Using it

function describeSelection() composes its answer from three reads — select.value, select.selectedIndex, and select.options[select.selectedIndex]?.text.

Look for the selected: $ prefixes when the file runs; they tie each line to its step.

Key statements

return `${select.value} @ index ${select.selectedIndex} (${option?.text ?? "none"})`;
select.addEventListener("change", () => {
console.log(describeSelection());
// selectedOptions 处理 multiple 场景:单选时长度恒为 1
const chosen = [...select.selectedOptions].map((option) => option.value);
console.log(`selected: ${chosen.join(",")}`);
});
if (!select) throw new Error("select markup missing");

Interactive Tools for This Topic

FAQ

Is there a failure path for bad input?
The code throws `Error` — the guard `!select` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
Does select Element Reads Selected Options 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.