Programming
Web Development
HTML
JavaScript
Form Handling

Set select option 'selected', by value

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

To select an option in an HTML <select> element by its value, assign the desired value directly to the select element's value property. The browser matches the value against the available <option> elements and updates the selection automatically. This one-liner covers the vast majority of use cases, but multi-select controls, dynamic option lists, and framework-managed forms each require a slightly different approach.

The Standard Approach: Assign select.value

Given this markup:

html
1<select id="fruit-select">
2  <option value="apple">Apple</option>
3  <option value="orange">Orange</option>
4  <option value="banana">Banana</option>
5</select>

You select the banana option with a single line:

javascript
const select = document.getElementById("fruit-select");
select.value = "banana";

Under the hood, the browser iterates through the options collection, finds the first <option> whose value matches, and sets its selected property to true while clearing the previously selected option. You never need to loop manually for single-select controls.

Verifying That a Value Matched

If the value you assign does not match any option, the select element either resets to the first option or shows an empty selection depending on the browser. No exception is thrown. When the value comes from external data (an API, user input, a URL parameter), you should verify the outcome:

javascript
1const select = document.getElementById("fruit-select");
2const wanted = "pear";
3
4select.value = wanted;
5
6if (select.value !== wanted) {
7  console.warn(`No <option> matched value "${wanted}".`);
8  // Fallback: select a default or show an error state
9  select.value = "apple";
10}

This guard is especially important when options are rendered from server data that might be out of sync with the client.

Multi-Select Controls

For a <select multiple>, the value property still only reflects a single value. To select multiple options by value, iterate through the options and set selected on each one individually:

html
1<select id="tag-select" multiple>
2  <option value="js">JavaScript</option>
3  <option value="py">Python</option>
4  <option value="go">Go</option>
5  <option value="rs">Rust</option>
6</select>
javascript
1const select = document.getElementById("tag-select");
2const wantedValues = new Set(["js", "go"]);
3
4for (const option of select.options) {
5  option.selected = wantedValues.has(option.value);
6}

Using a Set here keeps lookup time constant regardless of how many values you need to match, which matters when both the option list and the wanted list are large.

To read back all selected values:

javascript
const selected = Array.from(select.selectedOptions).map(o => o.value);
console.log(selected); // ["js", "go"]

Triggering Change Event Handlers

Setting select.value programmatically updates the DOM but does not fire the change event. If other parts of your application rely on that event (validation logic, dependent dropdowns, analytics tracking), dispatch it explicitly:

javascript
const select = document.getElementById("fruit-select");
select.value = "orange";
select.dispatchEvent(new Event("change", { bubbles: true }));

The { bubbles: true } option ensures that event listeners attached to ancestor elements also receive the event, which matches native browser behavior when a user interacts with the control.

Selecting by Option Query

Sometimes you need to inspect or modify the option node itself rather than just updating the selection. In that case, query for the option directly:

javascript
1const option = document.querySelector('#fruit-select option[value="banana"]');
2if (option) {
3  option.selected = true;
4}

This is more verbose than assigning select.value, but it is useful when you also need to add a CSS class to the matched option, read its textContent, or check for disabled status before selecting.

Dynamic Option Lists

When options are populated asynchronously (fetched from an API, rendered by a template engine), you must wait until the options exist before setting the value. A common pattern:

javascript
1async function loadAndSelect(selectId, apiUrl, targetValue) {
2  const select = document.getElementById(selectId);
3  const response = await fetch(apiUrl);
4  const items = await response.json();
5
6  select.innerHTML = items
7    .map(item => `<option value="${item.id}">${item.name}</option>`)
8    .join("");
9
10  select.value = targetValue;
11
12  if (select.value !== targetValue) {
13    console.warn(`Value "${targetValue}" not found in loaded options.`);
14  }
15}

Attempting to set a value before the matching option exists will silently fail. This is one of the most frequent bugs in form initialization code.

Framework Approaches

In modern frameworks, you rarely manipulate the DOM directly. Here is how each major framework handles value selection:

javascript
1// React (controlled component)
2const [fruit, setFruit] = useState("banana");
3return (
4  <select value={fruit} onChange={e => setFruit(e.target.value)}>
5    <option value="apple">Apple</option>
6    <option value="orange">Orange</option>
7    <option value="banana">Banana</option>
8  </select>
9);
html
1<!-- Vue -->
2<select v-model="fruit">
3  <option value="apple">Apple</option>
4  <option value="orange">Orange</option>
5  <option value="banana">Banana</option>
6</select>
html
1<!-- Angular -->
2<select [(ngModel)]="fruit">
3  <option value="apple">Apple</option>
4  <option value="orange">Orange</option>
5  <option value="banana">Banana</option>
6</select>

In all three, the selection is driven by component state. You "select by value" by setting the state variable, and the framework handles the DOM update.

Comparison of Selection Methods

MethodBest ForFires change Event?Works With Multi-Select?
select.value = "..."Single-select, simple casesNoNo (single value only)
option.selected = trueMulti-select or per-option logicNoYes
querySelector + selectedNeed to inspect option before selectingNoYes
Framework binding (v-model, value)Framework-managed formsVia framework event systemDepends on framework
dispatchEvent(new Event("change"))Triggering downstream handlersYes (manually)N/A (used after any method)

Common Pitfalls

Setting the selected HTML attribute and expecting it to remain authoritative after JavaScript modifies the control is a frequent mistake. Once the page is interactive, DOM properties (option.selected) take precedence over the original markup attribute.

Confusing an option's display text with its value is another common error. The browser matches against the value attribute, not the visible label. If your options look like <option value="us">United States</option>, you must set select.value = "us", not select.value = "United States".

Forgetting to dispatch the change event after programmatic updates leads to subtle bugs where dependent UI elements get out of sync.

Setting select.value before dynamic options have been rendered is a silent failure that produces no error message, making it hard to debug in production.

In React, placing selected on individual <option> elements instead of using the value prop on <select> produces a console warning and inconsistent behavior.

Summary

  • The standard way to select by value is select.value = "desired-value". The browser handles the matching.
  • Verify the result when the value comes from external or unreliable data.
  • For multi-select controls, loop through select.options and set selected on each matching option.
  • Dispatch a change event explicitly if downstream code depends on it firing.
  • In framework code, drive selection through state (useState, v-model, ngModel) rather than direct DOM manipulation.
  • Always ensure options are present in the DOM before attempting to set a value programmatically.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.