jQuery Dynamically Combobox Value Based on URL

Sam Deering
Tweet

Little jQuery function to dynamically set the value of a combo box based on the parameters given in the URL string. Could be useful for setting default values on a form results page based upon what the user selected for the search criteria.

This function works when you don’t have parameters specified in the url (ie not “param=1&param=2″) but when the url could have one huge paramter for an SQL query like “select=fields+from+table+like+combovaluevalue+etc”. You specify what string comes before the value you are looking for (ie find like we will get value combovaluevalue).

/* This function sets the combobox with the value after "like" inside the url */
(function($) { 
//get the url variables and set the combo box
var comboBox = $(location).attr('href');         
comboBox = decodeURIComponent(comboBox);  //decode url string
comboBox = comboBox.replace(/"/g, '');    //replace quotes    
var urlArray = comboBox.split("+");             //get params
//the param we're looking for is after "like"
comboBox = urlArray[jQuery.inArray("like", urlArray)+1];
$('#combobox-id > option').each(function(index) {
    //alert($(this).text() + ' ' + $(this).val());
    console.log(index + " " + $(this).attr('value'));
    if ($(this).attr('value') === comboBox) {
        comboBox = index;
    }
});
$('#combobox-id').attr('selectedIndex', jQuery.inArray(comboBox, urlArray));
})(jQuery);

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.