jQuery Dynamically Combobox Value Based on URL

By Sam Deering

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

Free Guide:

7 Habits of Successful CTOs

"What makes a great CTO?" Engineering skills? Business savvy? An innate tendency to channel a mythical creature (ahem, unicorn)? All of the above? Discover the top traits of the most successful CTOs in this free guide.

Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.