Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How can I get the selected value of a drop-down list with jQuery?
With jQuery, it's easy to get selected text from a drop-down list. This is done using the select id. To get the selected value of a drop-down list, use the val() method, and to get the selected text, use the text() method with the :selected selector.
Getting Selected Value and Text
There are several ways to retrieve information from a selected dropdown option ?
Getting Selected Value: Use $("#selectId").val() to get the value attribute of the selected option.
Getting Selected Text: Use $("#selectId option:selected").text() to get the display text of the selected option.
Example
You can try to run the following code to learn how to get the selected value of a drop-down list. This example demonstrates both getting the current selection and programmatically changing the selection ?
<html>
<head>
<title>jQuery Dropdown Selection</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#button1").click(function(){
// Get current selected value and text
var currentValue = $("#myselection").val();
var currentText = $("#myselection option:selected").text();
alert("Current selection - Value: " + currentValue + ", Text: " + currentText);
// Change selection to second option
$("#myselection").val('2');
// Show new selection
var newText = $("#myselection option:selected").text();
alert("New selection: " + newText);
});
});
</script>
</head>
<body>
<div>
<p>Select an option:</p>
<select id="myselection">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
</div>
<br>
<button id="button1">Get Selected Value</button>
</body>
</html>
The output will show two alert boxes: first displaying the currently selected option's value and text, then showing the new selection after programmatically changing it to "Second".
Conclusion
jQuery provides simple methods to work with dropdown selections: use val() to get or set the selected value, and option:selected with text() to retrieve the display text of the selected option.
