Datalist Combobox With Validity Guard
input.list exposes the bound datalist element and datalist.options enumerates suggestions, so free-typed values get a manual membership check.
Code
const input = document.querySelector<HTMLInputElement>('input[list]');
const datalist = document.querySelector<HTMLDataListElement>('datalist');
if (!input || !datalist) throw new Error('combobox markup missing');
// input.list exposes the bound datalist element
console.log('list bound to:', input.list === datalist);
const options = Array.from(datalist.options).map((option) => option.value);
console.log('options:', options.join(', '));
// Free typing is allowed; membership against the option list is manual
const value = input.value.trim();
console.log('typed value:', value, 'known:', options.includes(value));
if (!options.includes(value)) {
input.setAttribute('aria-invalid', 'true');
}
console.log('aria-invalid:', input.getAttribute('aria-invalid'));How it works
The failure path is explicit — Error is raised when the guard condition holds.
The file’s state is a handful of top-level bindings: input, datalist, options, value.
What to watch for
- Nothing third-party is pulled in; the snippet is dependency-free.
documentexist only in browsers — a Node runtime has no shims for them out of the box.- The guard
!input || !dataliststops the pass immediately with an earlythrowwhen its condition holds.
Using it
Look for the list bound to:, options:, typed value: prefixes once the file starts running; each one ties a printed line to the step that produced it.
Key statements
const options = Array.from(datalist.options).map((option) => option.value);
if (!input || !datalist) throw new Error('combobox markup missing');
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- How does the code behave when input is bad?
- `Error` is raised at the guard (`!input || !datalist`), so invalid state never reaches the main logic.
- Does Datalist Combobox With Validity Guard 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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.