Get selected text from a drop-down list with JavaScript/jQuery
This post will discuss how to get selected text from a dropdown list in JavaScript and jQuery.
1. Using jQuery
With jQuery, you can use the text() or html() method to get the selected text from a dropdown. This can be done in several ways using the :selected property to get the chosen option of the select element, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
$("#pets option:selected").text(); $("#pets :selected").text(); $(":selected", $("#pets")).text(); $("#pets option").filter(":selected").text(); $("#pets").children("option").filter(":selected").text(); $("#pets").children("option:selected").text(); $("#pets").find("option:selected").text(); |
Here’s a live example:
JS
|
1 2 3 4 5 |
$(document).ready(function() { $('#submit').click(function() { $('#container').html(`The selected text is ` + $("#pets option:selected").text()); }) }); |
HTML
|
1 2 3 4 5 6 7 8 9 10 11 |
<label for="pets">Choose your pets:</label> <select name="pets" id="pets"> <option value="dog">Dog</option> <option value="cat">Cat</option> <option value="rabbit">Rabbit</option> <option value="parrot">Parrot</option> </select> <button id="submit">Get Selected Text</button> <div id="container"></div> |
2. Using JavaScript
In plain JavaScript, you can do like:
JS
|
1 2 3 4 5 |
document.getElementById('submit').onclick = function() { var e = document.getElementById("pets"); var text = e.options[e.selectedIndex].text; document.getElementById("container").innerHTML = 'The selected text is ' + text; } |
HTML
|
1 2 3 4 5 6 7 8 9 10 11 |
<label for="pets">Choose your pets:</label> <select name="pets" id="pets"> <option value="dog">Dog</option> <option value="cat">Cat</option> <option value="rabbit">Rabbit</option> <option value="parrot">Parrot</option> </select> <button id="submit">Get Selected Text</button> <div id="container"></div> |
That’s all about getting selected text from a drop-down list in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)