jQuery Tutorial

jQuery Examples

jQuery Practice

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.



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



<!DOCTYPE html>

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

jQuery Function:

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

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


Example: Select an option by its text

Comments and Discussions!

Load comments ↻

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