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);
Sam Deering is a Front-end Web Developer who specialises in JavaScript & jQuery. Sam is driven and passionate about sharing his knowledge to educate others.

Free Guide:

How to Choose the Right Charting Library for Your Application

How do you make sure that the charting library you choose has everything you need? Sign up to receive this detailed guide from FusionCharts, which explores all the factors you need to consider before making the decision.


Learn JavaScript for free!
Free course: Introduction to JavaScript

Yours when you take up a free 14-day SitePoint Premium trial.