Programming
Web Development
HTML
JavaScript
Form Handling

How to set a select option as selected by value in JavaScript

Codemia Knowledge Hub ·

Assign the value to the <select> element's value property. The browser matches it against the available <option> elements and updates the selection. Multi-select controls, dynamic option lists, and framework-managed forms each need a slightly different approach, covered below.

Assigning 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>

Select the banana option with one line:

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

The browser iterates through the options collection, finds the first <option> whose value matches, sets its selected property to true, and clears the previously selected option. For single-select controls you never need to loop manually.

The match is against the value attribute, not the visible label. For <option value="us">United States</option>, set select.value = "us", not "United States".

Verifying that a value matched

If the assigned value matches no option, every option is deselected: selectedIndex becomes -1 and a single-select shows an empty selection. No exception is thrown. When the value comes from external data (an API, user input, a URL parameter), check 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 matters most when options are rendered from server data that might be out of sync with the client.

Selecting several values in a <select multiple>

For a <select multiple>, value only reflects a single value. Iterate through options and set selected on each one:

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}

A Set keeps lookup time constant regardless of how many values you match, which helps when both lists are large.

To read back all selected values:

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

Firing the change event

Setting select.value programmatically updates the DOM but does not fire change. If validation logic, dependent dropdowns, or analytics rely on that event, dispatch it yourself:

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

{ bubbles: true } lets listeners on ancestor elements receive the event, matching native behavior when a user interacts with the control. Forgetting this leads to dependent UI elements getting out of sync.

Querying the option element directly

When you need the option node itself, query for it:

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

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

Options loaded asynchronously

When options are fetched from an API or rendered by a template engine, wait until they exist before setting the value:

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}

Setting a value before the matching option exists fails silently with no error message. It is one of the most frequent bugs in form initialization code and hard to debug in production.

React, Vue and Angular

In frameworks, selection is driven by component state rather than direct DOM manipulation:

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>

You "select by value" by setting the state variable, and the framework updates the DOM. In React, placing selected on individual <option> elements instead of using the value prop on <select> produces a console warning and inconsistent behavior.

The selected attribute versus the property

Setting the selected HTML attribute and expecting it to stay authoritative after JavaScript modifies the control is a common mistake. Once the page is interactive, the DOM property (option.selected) takes precedence over the original markup attribute.

Comparing the 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)

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
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms