Programming Tutorials

Handling Select options in JavaScript

By: aathishankaran in JavaScript Tutorials on 2007-03-27  

In HTML, a <select> element creates a drop-down list. The options in the drop-down list can be accessed and manipulated using JavaScript.

To get the selected option from a <select> element, you can use the selectedIndex property and the options property of the element. 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>

<script>
  const selectElement = document.getElementById("mySelect");
  const selectedOption = selectElement.options[selectElement.selectedIndex].value;
  console.log(selectedOption); // prints the value of the selected option
</script>

To change the selected option in a <select> element using JavaScript, you can set the selectedIndex property to the index 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="changeOption()">Change option</button>

<script>
  const selectElement = document.getElementById("mySelect");
  
  function changeOption() {
    selectElement.selectedIndex = 1; // selects the second option
  }
</script>





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in JavaScript )

Latest Articles (in JavaScript)