Set the Value of a Select Dropdown Using Its Options’ Text Labels

Code

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.

<select id="state" name="state">
   <option value="UT">Utah</option>
   <option value="CO">Colorado</option>
   <option value="AZ">Arizona</option>
   <option value="NM">New Mexico</option>
</select>

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

(function($) {
    $(document).ready(function(){

        // Either of these will work
        var select_state = 'AZ';
        var select_state = 'Arizona';

        if($('select#state option[value="' + select_state +'"]').length == 0) {
            // State dropdown has no matching values... try the text labels instead
            select_state = $('select#state option').filter(function() {
                // Filter to find the option where the label (html) matches the state name
                return $(this).html() == select_state;
            }).val(); // Get the value of that option 
        }
        $('select#state').val(select_state);

    });
})(jQuery);

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.

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments