Asked 2 years ago
29 Jun 2021
Views 406
Taryn

Taryn posted

How do I programmatically set the value of a select box element

How do I programmatically set the value of a select box element
QuickIos

QuickIos
answered Apr 28 '23 00:00

To programmatically set the value of a select box element in JavaScript, you can set the value property of the select element to the value of the option you want to select. Here's an example:



<select id="mySelect">
  <option value="option1">Option 1</option>
  <option value="option2">Option 2</option>
  <option value="option3">Option 3</option>
</select>

<button onclick="selectOption()">Select Option 2</button>

<script>
function selectOption() {
  var selectBox = document.getElementById("mySelect");
  selectBox.value = "option2"; // set the value of the select box to "option2"
}
</script>

In this example, we have a select box with three options , and a button that calls the selectOption () function when clicked. Inside the function, we first select the select box element using its ID, and then we set its value property to "option2", which is the value of the second option.

When the button is clicked, the select box will automatically select the second option because its value has been set to " option2 ". You can modify the code to select a different option or set a different value based on your specific needs.
Post Answer