Select option from dropdown select tag by text instead of value in jQuery

In most of the time, we generally select an option from an HTML select box by the value of that option. But did you ever think about selecting an option by the text of that option?

Here we are going to select an option by its text instead of the value in jQuery. Using jQuery we will find the particular text and then set the option contains the text.

How to reload an iframe in jQuery?

Now see the example:

Below is our HTML code for the drop-down select box which contains a button also:

<select id="myDropdown">
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
  <option value="3">Option 3</option>

<button id="selectOption">Select</button>

Now below is the jQuery code:

$( "#selectOption" ).click(function() {
  $("#myDropdown option:contains(Option 2)").attr('selected', 'selected');

Now let’s check it.

When we run our code on browser then if we click the button, we will see that the option with text “Option 2” with the value “2” selected.

Simple Animation Example Using jQuery

Check whether a checkbox is checked in jQuery

Here we have set jQuery click() method on the button with id “selectOption”. So when we click on the button, our jQuery code will find the option from the select tag which contains “Option 2” and adds the attribute “selected”. Adding the “selected” attribute means selecting the option.

Now we are able to select an option by its text using the simple and easy to use jQuery code. Only one line of jQuery did this task. Here the one line code is:

$("#myDropdown option:contains(Option 2)").attr('selected', 'selected');

The code adding the attribute “selected” to the option contains the text “Option 2”.


7 responses to “Select option from dropdown select tag by text instead of value in jQuery”

  1. CodeBlogs says:

    var myText = “Pakistan”;
    $(“#CountryDropDownList option:contains(” + myText + “)”).attr(‘selected’, ‘selected’);

    • Faruque says:

      Contains has a problem that is , it cannot select exact words, such as it will select both xx and xxx when myText = xx

      • Anupam says:

        What to use instead of `option: contains` to get an accurate value. Because when I select color `L` It will show `XL`

  2. Rashid says:

    big thanks, man…………. I was really struggling to get it done…

  3. zee says:

    How to pass this selected text to the PHP session?
    help, please

    • Faruque Ahamed Mollick says:

      Well, you can do it with AJAX. You just need to send the variable via AJAX and there you can pass it using PHP.

  4. tsh says:

    Thanks a lot. Saved my day

Leave a Reply

Your email address will not be published. Required fields are marked *