JavaScript
Article

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));
})(jQuery);
Sam Deering
Meet the author
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.

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

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