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

Spread the love

Sometimes, we want to programmatically set the value of a select box element using JavaScript.

In this article, we’ll look at how to programmatically set the value of a select box element using JavaScript.

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

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

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 a select element.

Then we write

const leaveCode = document.querySelector("#leaveCode");
leaveCode.value = "14";

to call querySelector to select the select element.

Then we set its value property to '14' to select the option with value attribute set to 14.

Conclusion

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

Leave a Reply

Your email address will not be published. Required fields are marked *