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

By Faruque Ahamed Mollick

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>
</select>

<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”.

 

Tags:

Leave a Reply

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