Asked 2 years ago
29 Jun 2021
Views 363
Brown

Brown posted

Change option value of select box on calling function

Change option value of select box on calling function
shyam

shyam
answered Apr 28 '23 00:00

Here's a possible way to rewrite the answer to avoid duplicate content:

To change the value of an option in a select box when calling a function in JavaScript, you can use the options property of the select element to select the desired option element, and then set its value attribute to the new value.

Here's an example code snippet that demonstrates how to change the value of the second option in a select box with the ID mySelect to "newOptionValue" when a button is clicked:



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

<button onclick="changeOptionValue()">Change option value</button>

<script>
function changeOptionValue() {
  var selectBox = document.getElementById("mySelect");
  var option = selectBox.options[1]; // select the second option
  option.value = "newOptionValue"; // change the value of the option
}
</script>

In this code, we first select the select box element using its ID, and then we select the second option by accessing the options property of the select box and passing its index (which is zero-based) to the array-like options object. We then set the value of the option to "newOptionValue".

You can modify this code to select a different option or set a different value based on your specific needs.
Post Answer