Categories
JavaScript Answers

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

Spread the love

To programmatically set the value of a select box element using JavaScript, we set its value property.

For instance, we write

<select id="leaveCode" name="leaveCode">
  <option value="10">Annual Leave</option>
  <option value="11">Medical Leave</option>
  <option value="14">Long Service</option>
  <option value="17">Leave Without Pay</option>
</select>

to add the select drop down.

Then we write

const element = document.getElementById("leaveCode");
element.value = "11";

to select the drop down with getElementById.

And we set its value property to the value attribute of the option we want to select.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.