jQuery | Which selector do I need to select an option by its text?

In this tutorial, we will discuss how can we select an option by its text and not using value in jQuery?
Submitted by Pratishtha Saxena, on July 08, 2022

Generally, we use the value of an option tag to select that particular option. But what if we need to select the option by its text. Then for this, we'll use :contains() selector of jQuery.

The contains() selector selects all the elements/options that contain the specified text within the brackets. The specified text can be present anywhere in the element or even in its child element. But the text here is case sensitive, which means "abc" and "ABC" will be treated as two different strings.

Syntax:

$(":contains(text)");
$("div:contains(abc)");

Here, it will check whether any div element contains the text "abc". Let's understand this better with an example.

Example:

HTML:

<!DOCTYPE html>

<html lang="en">
   <head>
      <meta charset="UTF-8">
      <title>Title</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
   </head>
   
   <body>
      <center>
         <h2>Devices</h2>
         <select id="mySelect">
            <option value="one">Laptop</option>
            <option value="two">Watch</option>
            <option value="three">Mobile</option>
         </select>
         &nbsp;&nbsp;&nbsp;
         <button id="selectOption1">Select Watch</button>
         <button id="selectOption2">Select Mobile</button>
      </center>
   </body>
   
</html>

jQuery Function:

<script>
    $( "#selectOption1" ).click(function() {
      $("#mySelect option:contains(Watch)").attr('selected', 'selected');
    });

    $( "#selectOption2" ).click(function() {
      $("#mySelect option:contains(Mobile)").attr('selected', 'selected');
    });
</script>

Output:

Example: Select an option by its text





Comments and Discussions!

Load comments ↻





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