Get selected value in dropdown list using JavaScript
The selectedIndex property is utilized to both retrieve and set the index of the selected option within a dropdown list. This index corresponds to the position of the option within the list and can be manipulated through JavaScript to manage the selected option dynamically.
- Get from selectedIndex property.
selectObject.selectedIndex
- Set the Select selectedIndex property.
selectObject.selectedIndex = number
The index starts at 0 and if no element is selected then it return -1. If the drop-down list allows multiple selections it will only return the index of the first option selected.
Browser View
Full Source | JavaScript
<!DOCTYPE html>
<html>
<body>
<div>
<select id="items">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3" selected="selected">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
<br><br>
<button onClick="GetSelectedItem('items');">Get Selected Item</button>
</div>
<script>
function GetSelectedItem(sItem)
{
var i = document.getElementById(sItem);
var strSel = "Value is: " + i.options[i.selectedIndex].value + " and Text is: " + i.options[i.selectedIndex].text;
alert(strSel);
}
</script>
</body>
</html>
jQuery
$("#elementId :selected").text(); // The text content of the selected option
$("#elementId :selected").val(); // The value of the selected option
Conclusion
To obtain the selected value from a dropdown list in JavaScript, retrieve the dropdown element and access its value property. This straightforward approach enables you to retrieve and process the chosen option easily.
Related Topics
- JavaScript Popup Boxes
- Opening a new window in JavaScript
- How to Create Drop-Down Lists in JavaScript
- How do I include a JavaScript file in another JavaScript file?
- Print the content of a Div using JavaScript/jQuery
- How to get the current URL using JavaScript ?
- How to Detect a Mobile Device with JavaScript/jQuery
- How to validate an email address in JavaScript
- JavaScript Array Iteration
- How to Remove a Specific Item from an Array in JavaScript
- What is JavaScript closures?
- How To Remove a Property from a JavaScript Object
- How do I get the current date in JavaScript?
- How to Open URL in New Tab | JavaScript
- How to delay/wait/Sleep in code execution | JavaScript
- How to round to at most 2 decimal places | JavaScript
- How to convert string to boolean | JavaScript
- How to check undefined in JavaScript?
- How To Copy to Clipboard | JavaScript
- How to encode a URL using JavaScript?
- How to force Input field to enter numbers only | JavaScript
- How to create multiline string in JavaScript
- How to Check for an Empty String in JavaScript?