How to get selected value in dropdown list using JavaScript ?

To get the selected value from a dropdown list (HTML <select> element) using JavaScript, you can use the value property of the <select> element. Here’s how to do it:

1. Basic Method

HTML:

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

JavaScript:

// Get the selected value
const selectElement = document.getElementById("mySelect");
const selectedValue = selectElement.value;

console.log(selectedValue); // e.g., "2" (the value of the selected option)

2. Get the Display Text (Not the Value)

To retrieve the text of the selected option (e.g., “Option 2”):

const selectedText = selectElement.options[selectElement.selectedIndex].text;
console.log(selectedText); // e.g., "Option 2"

3. Listen for Selection Changes

Use the change event to update when the user selects a new option:

selectElement.addEventListener("change", function() {
  console.log("New value:", this.value);
  console.log("New text:", this.options[this.selectedIndex].text);
});

4. Example with a Button

<select id="mySelect">
  <option value="apple">Apple</option>
  <option value="banana">Banana</option>
</select>
<button onclick="getSelectedValue()">Get Value</button>

<script>
  function getSelectedValue() {
    const select = document.getElementById("mySelect");
    alert("Selected value: " + select.value);
  }
</script>

Key Notes

  • value vs text:
  • selectElement.value → Returns the value attribute of the selected <option>.
  • selectElement.options[selectElement.selectedIndex].text → Returns the displayed text of the selected <option>.
  • selectedIndex: Returns the index of the selected option (starts at 0).
  • No Selection: If no option is selected, selectedIndex is -1.

Edge Cases

Handling No Selection:

if (selectElement.selectedIndex === -1) {
  console.log("No option selected!");
}

Multi-Select Dropdowns:

For <select multiple>, iterate over all selected options:

const multiSelect = document.getElementById("multiSelect");
const selectedValues = Array.from(multiSelect.selectedOptions)
  .map(option => option.value);

console.log(selectedValues); // e.g., ["1", "3"]

Summary

  • Use selectElement.value to get the selected value.
  • Use selectElement.options[selectElement.selectedIndex].text to get the displayed text.
  • Attach a change event listener to react to user selections.

Leave a Reply

Your email address will not be published. Required fields are marked *