Get selected text from a drop-down list (select box) using jQuery

Here, we'll see how to get the selected text (not the selected value) from a drop-down list using jQuery?
Submitted by Pratishtha Saxena, on May 28, 2022

With jQuery, it's easy to get selected text from a drop-down list with :selected. This is done using the select id. The option:selected method is a way in jQuery which is used to return the selected element from a list of the element. No parameters are required for this.

Syntax:

$("#selector option:selected");

Note: Always make sure to include the jQuery CDN link in the script tag whenever working with jQuery.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

First, we'll create a drop-down list using an HTML select tag and add options to it with some values (here – 1,2). The text here is Hindi, and English. Also, a button is specified which when clicked will alert the text of the option selected.

To get the text of the selected value, we'll create a function that will alert and display the selected text.

Example:

HTML Code:

<html>
   <head>
      <title>Title</title>
   </head>
   <body>
      <div>
         <p>Select Value:</p>
         <select id="myselection">
            <option value="1">Hindi</option>
            <option value="2">English</option>
         </select>
         <br>
         <br>
         <button id="submit">Submit</button>
      </div>
   </body>
</html>

jQuery Function:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script>
    $(document).ready(function() {
        $("#submit").click(function() {
            var value = $("#myselection option:selected");
            alert(value.text());
        });
    });
</script>

Output:

Example: Get selected text from a drop-down list


ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.