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

Estimated read time 2 min read

Here is an example to programmatically set the value of a select box element using JavaScript:

<!DOCTYPE html>
<html>
  <head>
    <title>Set Select Box Value Example</title>
  </head>
  <body>
    <select id="mySelect">
      <option value="option1">Option 1</option>
      <option value="option2">Option 2</option>
      <option value="option3">Option 3</option>
    </select>
    <button id="myButton">Set Value</button>
    <script>
      var select = document.getElementById("mySelect");
      var button = document.getElementById("myButton");

      button.addEventListener("click", function() {
        select.value = "option3";
      });
    </script>
  </body>
</html>

This code creates a simple HTML page with a select box and a button. When the button is clicked, the value of the select box is set to "option3" using JavaScript. The JavaScript code uses the document.getElementById method to select the select box and the button elements, and the addEventListener method to attach a click event listener to the button. The event listener updates the value of the select box using the value property.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply