In this article, we will see how to achieve Jquery Dropdown Selected Value contains. This example will useful when we want to get some value that will be selected when we change the option of a select element in HTML. In this article I just want to explain is that users get value by selecting an option from dropdown using jQuery.

As we are seeing that 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?

How to check Jquery Dropdown Selected Value contains?

In this topic we going to see how to achieve Jquery Dropdown Selected Value contains for that here we are going to select an option by its text instead of the value in jQuery.

For that we will be going to use jQuery we will find the particular text and then set the option contains the text.

Below is example of HTML code having drop-down select box which contains nothing but a button also, so going to look into this:

<!doctype html><html lang="en"><head> <meta charset="utf-8"> <title>contains demo</title> <script src="https://code.jquery.com/jquery-3.5.0.js"></script></head><body><select id="myDropdownId"> <option value="1">PHP 1</option> <option value="2">Jquery 2</option> <option value="3">Magento 3</option></select><button id="selectOptionId">Select</button><script>$( "#selectOptionId" ).click(function() { $("#myDropdownId option:contains(Jquery 2)").attr('selected', 'selected');});</script> </body></html>

Now let’s check this above code.

When we going to run this code in the browser then if we going click above button which is declared in HTML tag, we will get the result that the option with the text “Jquery 2” with the value “2” selected.

Allow Only Numbers and One Dot in Textbox jQuery Regex

Jquery check if table contains text

In this we have set jQuery click() method on the button link with id “selectOptionId”.

So when we going to click on the button link, our nothing but the jQuery code will find the option from the select tag which contains text called “Jquery 2” and finally it will adds the attribute “selected”.

By Adding this “selected” attribute means selecting the option of select tag.

Now we can say that with the help of below code we are able to select an option by its text using jQuery code. Only single line of jQuery did this task successfully. The single line of code is given below:

$("#myDropdownId option:contains(Jquery 2)").attr('selected', 'selected');

This above code, main use adding attribute “selected” to the option contains the text “Jquery 2”.

I hope you liked my this article. If you have any queries or any question regarding this, Feel free to comment on Me.