I have a dropdown list like this:
<form>
<select id="ddlViewBy">
<option value="1">test1</option>
<option value="2" selected="selected">test2</option>
<option value="3">test3</option>
</select>
</form>
How can I retrieve the selected option value from a dropdown list using JavaScript?
Hi Mehta,
Simple Access via value
Property (Most Common Way):
const selectedValue = document.getElementById('ddlViewBy').value;
console.log(selectedValue); // e.g., "2"
This is the easiest and most widely used method. Works like a charm for getting the value of the selected option.
You can also access the selected option element itself :
Use the snippet below, it will work if you need the displayed text rather than just the value.
const dropdown = document.getElementById('ddlViewBy');
const selectedText = dropdown.options[dropdown.selectedIndex].text;
console.log(selectedText); // e.g., "test2"
If you want to do something custom, try running a loop through options:
const dropdown = document.getElementById('ddlViewBy');
for (let i = 0; i < dropdown.options.length; i++) {
if (dropdown.options[i].selected) {
console.log(`Selected value: ${dropdown.options[i].value}`);
console.log(`Selected text: ${dropdown.options[i].text}`);
}
}
This is great when handling multi-selects or adding extra logic during selection.