ADVERTISEMENT
ADVERTISEMENT

jQuery: Get specific option tag text

In this tutorial, you'll learn how to get the text of the selected option tag?
Submitted by Pratishtha Saxena, on June 10, 2022

jQuery is a JavaScript library used to simplify HTML DOM tree traversal, event handling, etc.

Now, to display the text of the selected option tag using jQuery, a selector is used.

Using :selected Selector

The :selector selects the option tag that is already selected. It is very easy to select the text in jQuery using this selector. 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: Don't forget to apply to jQuery CDN link in the script tag while working with jQuery.

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

When :selected is used with the val() method, it returns the value of the selected option tag.

But this cannot be used to get text from checkboxes and radio buttons. For that, :checked selector is used.

Example:

HTML Code:

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <title>Title</title>
      <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
   </head>
   <body>
      <form>
         <label>Select Fruit:</label>
         <select class="fruit">
            <option value="apple">Apple</option>
            <option value="mango">Mango</option>
            <option value="watermelon">Watermelon</option>
            <option value="orange">Orange</option>
            <option value="grapes">Grapes</option>
            <option value="banana">Banana</option>
         </select>
      </form>
   </body>
</html>

jQuery Function:

<script>
$(document).ready(function(){
    $("select.fruit").change(function(){
        var selectedFruit = $(this).children("option:selected").val();
        alert(selectedFruit);
    });
});
</script>

Output:

Example: Get specific option tag text


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

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.