×

jQuery Tutorial

jQuery Examples

jQuery Practice

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





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.