2

Using jQuery, what is the easiest way to select an item in a drop down list using the text value.

For example, I have drop down list that has a list of states. And I have the text value of “PA”. I want to make “PA” be the selected value. What is the best way to do this using jQuery. I have been doing Google searches for hours and I cannot find an example to this question.

Note each item in the drop down list has a numeric key. And I know that $(#ddlStates).val(key) will select the value I want. However, I do not have the key only the test (“PA”)

Thanks for your help.

2 Answers 2

6

To be 100% sure on the match you can do this:

$("#ddlStates option").filter(function() {
  return $(this).text() == "PA";
}).attr('selected', true);

What will probably work for your scenario is the :has() selector, less safe in others is just:

$("#ddlStates option:contains('PA')").attr('selected', true);

You can test it out here, you wouldn't want to use this in other cases because it would match a substring, but since you have states, presumably all 2 letters it will work here. For other cases you can use the first method.

Sign up to request clarification or add additional context in comments.

Comments

0
$("#myselect :selected").text(); 

see this post Get selected text from a drop-down list (select box) using jQuery

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.