How to get selected value in dropdown list using JavaScript ?


To get the selected value in a dropdown list using JavaScript, you can use the value property of the select element. Here are some methods to achieve this:

Method 1: Using the value property

HTML code:

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

JavaScript code:

const selectElement = document.getElementById("mySelect");
const selectedValue = selectElement.value;
console.log(selectedValue);

In this method, we first get the select element using its id attribute. Then, we access its value property to get the selected option's value.

Method 2: Using the selectedIndex property

HTML code:

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

JavaScript code:

const selectElement = document.getElementById("mySelect");
const selectedIndex = selectElement.selectedIndex;
const selectedValue = selectElement.options[selectedIndex].value;
console.log(selectedValue);

In this method, we first get the select element using its id attribute. Then, we access its selectedIndex property to get the index of the selected option. Finally, we use the options property to get the selected option and access its value property.

Method 3: Using the onchange event

HTML code:

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

JavaScript code:

function getSelectedValue() {
  const selectElement = document.getElementById("mySelect");
  const selectedValue = selectElement.value;
  console.log(selectedValue);
}

In this method, we add an onchange event to the select element that calls a function getSelectedValue(). Inside this function, we get the select element using its id attribute and access its value property to get the selected option's value.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.