jQuery Dynamically Combobox Value Based on URL

Share this article

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 DeeringSam Deering
View Author

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

jQuery
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week