How to programmatically set the value of a select box element using JavaScript?


We can set the value of a select box using Javascript using the following. Suppose we have the following select box −

<select id="my-select" value="1">
   <option value="1">Select</option>
   <option value="2">Apple</option>
   <option value="3">Strawberry</option>
   <option value="4">Cherry</option>
   <option value="5">Guava</option>
</select>

To set the value of this select element, we need to access it using querySelector. Then set the value. For example −

Example

// Search the select box
const mySelectBox = document.querySelector('#my-select');
// Set the value to 3 or Strawberry
mySelectBox.value = 3;

Updated on: 27-Nov-2019

625 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements