jQuery: Selecting an item in a drop down list using the text value
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 stat开发者_JS百科es. 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.
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.
$("#myselect :selected").text();
see this post Get selected text from a drop-down list (select box) using jQuery
精彩评论