Ever run into the problem where you have a string, and you need set the value of a select dropdown to that string, but the string you have may not match any of the option values, but instead might match the label of an option?

I ran into that and devised this nice solution that worked out very well.

The Problem

Here is an example of the select dropdown of states.

The problem is that you have an incoming variable that could be “AZ”, or it could be “Arizona”.  How can you set the value of the select dropdown since out of the box, only “AZ” would work for setting the value.  If you get “Arizona”, then it wouldn’t work.

My jQuery Solution

My solution uses jQuery, and the key to it is the .filter() .

In my example the select dropdown field is a list of states, and the string that I have to work with could either be the state abbreviation (AZ), or the full state name (Arizona).

The Code Explained

The code first checks to see if the state select dropdown has any option values that match the string.

If it doesn’t find any, then it will filter all of the option to find the one whose html matches the string and gets the value of that option, storing that value in the same string variable, overwriting it.

Finally, it simply sets the select field’s value to that variable.

Pretty Cool, Huh?

Let me know what you think.

Did this work out really well for you?

Need help getting this to work with your situation?

Leave a comment below.

Leave a Reply

avatar
  Subscribe  
Notify of