Generating a Dynamic Selection DropDown with jQuery and AJAX

jQuery makes it easy to pull in dynamic content using the built in AJAX module. With a few simple steps you will be able to pull content from an XML file and generate a form dropdown that the user can select from.

View the demo to see the dropdown in action.

  1. Loading Data with the jQuery AJAX Component
  2. Populate a Select Dropdown Using the Loaded XML Data
  3. Bind Data using the Data Module
  4. Call an Action When the Dropdown Has Changed
  5. Once the User has Finished all Selections Do Something Else

Loading Data with the jQuery ajax Component

There are only a few parameters needed to pull in data using jQuery’s ajax module. Once your document is ready for jQuery initialize the ajax by calling the proper function. I have setup a loadXML function that passes a string for the path to the XML file. The ajax object requires only a couple parameters with many more optional parameters: url (the path to your file), and success (the method that gets called on success). I will usually specify the dataType to ensure the correct data-type is being referenced. To get the full list of optional parameters see the jQuery.ajax documentation.

function init(){
		$("#languageList").hide();
		loadXML("langSelections.xml");
	}
	function loadXML(_xmlFile){
	$.ajax({
			 url: _xmlFile,
			 success: setXML,
			 dataType: "xml",
			 type: "GET",
	}) // close ajax

Here is the sample XML that I am using in the demo for a country selection dropdown:

<countries>
	<country program="1">
		<label>United States</label>
		<languages>
			<language langCode="en_US">English</language>
		</languages>
	</country>
	<country program="13">
		<label>Canada</label>
		<languages>
			<language langCode="en_US">English</language>
			<language langCode="ca_FR">Français</language>
		</languages>
	</country>
	<country program="10">
		<label>Mexico</label>
		<languages>
			<language langCode="en_US">English</language>
			<language langCode="es_MX">Español</language>
		</languages>
	</country>
</countries>

Populate a Select Dropdown Using the Loaded XML Data

Once the data has successfully loaded it is ready for use. The success parameter calls the setXML method and passes the data that was loaded. For simplicity in this demo, I set up a blank form with empty select tags prior to the data being loaded. This list can also be created using an unordered list where instead of the select and option tags within a form for greater styling control, but I’m keeping things simple here. Now, by using a simple loop in jQuery, you can append text to your form. By setting up a caching variable (i.e. “curCountry”), the DOM will not have to look up the node reference on each use speeding up your loop process. The “country” variable is set to the node of the current item in the loop as a jQuery object by using $(this) keyword. The “curOption” generates each option tag for the select dropdown list through concatenating a string of text with the values received from the node in the loop.

...
function setXML(_xml){
	var _idx=0;
	var curOption;
	var curCountry = $(_xml).find('country');
	$(curCountry).each(function(i){
		var country = $(this);
		curOption=$("<option value='" + $(country).attr('program') + "'>" + country.children('label').text() + "</option>")
	...

Here is the form found in the html with a default option:

<form id="selections" >
	<select name="countrySelect" onchange="setLanguage()" id="countryList">
		<option value="null">--Select Country--</option>
	</select>
	<select name="languageSelect" onchange="gotoPage()" id="languageList">
	</select>
</form>

Bind Data using the Data Module

It is best practice not to use global variables for an application; It is slower to look up a global variable, plus there are certain security issues surrounding global variables. By using the .data() module, you can bind portions of your data to specific elements within your page. Within my example I am binding the data from the current node (“country”) in the XML to the option/list item. By binding the data to an object, a whole array of data can be stored. Once the option is set with the proper data from the country node, append it to the corresponding select tag that was setup using the id of “countryList”.

...
	curOption.data("country",country); // bind the country node data from the XML to the option of the dropdown
	$(curOption).appendTo($('#countryList'))
	})
}

Call an Action When the Dropdown Has Changed

In my demo I have set the onchange="setLanguage()". Within "setLanguage" a second dropdown gets populated similar to how the first was created, with some slight differences. It is here the data that was bound to the selected option in "countryList" can be looked up and used to iterate through the languages and populate the options for the language dropdown. Since the "languageList" will get reset for each selected country, the HTML value is set to an empty string and then the options are set within the loop of the languages. Data binding was unnecessary for this loop, therefore to avoid appending the options multiple times, the "curOption" variable is generated as a string and concatonated within the loop. This way the options only need to be appended to the HTML of the parent ("languageList") one time, which saves on process time.

function setLanguage(){
	var curCountry = $('#countryList').children(':selected').data('country')
	$('#languageList').html(""); // reset the languages list
	var curLang = $(curCountry).find('language');
	if (curLang.length>1){
		curLang.each(function(i){
			var lang = $(this);
			var langCode=lang.attr('langCode');
			if (i==0){
				curOption="<option value='null'>--Select Language--</option><option value='" + langCode + "'>" + lang.text() + "</option>";
			}else{
				curOption+="<option value='" + langCode + "'>" + lang.text() + "</option>"
			}
		});
		$(curOption).appendTo($('#languageList'));
		$('#languageList').show()
	}else if (curCountry==null){
		$('#languageList').hide();
	}else{
		$('#languageList').hide();
		gotoPage($(curCountry).find('language').attr('langCode'))
	}
}

Once the User has Finished all Selections Do Something Else

I added some logic to check the number of children within the languages. If there is only one language, then there is no reason for the user to choose one, so it moves on to the next action of "gotoPage()", otherwise it will build the language dropdown and show it for the user to select. Once that selection has been made, "gotoPage()" is called and uses the selected country from "countryList" and the selected language. To illustrate how it could be used, I concatenate the values to form the desired URL.

function gotoPage(_lang){
	if (_lang==null){
		_lang = $('#languageList').val();
	}
	if (_lang!="null"){
		var _url = "http://myURL/" + $('#countryList').val() + "/"+ _lang;
		//window.open(_url) // optionally open a window using the XML data
		$('#linkURL').html(_url);
	}
}

As you get comfortable with jQuery, generating a dropdown with dynamic content can be easy using jQuery and Ajax. jQuery does most of the work for you. Once you have the basics of pulling in the content and parsing through the data as shown in this tutorial, you are well on your way to driving your site with a bit more more control.

  • Pingback: Customizable jQuery Drop-Down Menus, by @graphnick

  • Lan Xce

    exactly what  i needed thank you.

  • Prajakta

    This code is not working in Chrome… I tried on firefox.
    Please help it out

  • Pingback: Ajax programming - Turkish Living Forums

  • coolshaily

    superb… this is what I want thank you

  • LearnQigongOnline

    Hey, this is awesome stuff right here. AJAX is tricky for me but when i see well written code it’s much easier to understand. GREAT TUTORIAL and thanks a ton for sharing!

    • http://graphnickdesign.com Nicholas Thane Haroldsen

      Thank you. Well appreciated.

  • crapy craper

    well , …………..
    shit , i’ve got nothing

  • Nathaneal Ramesh

    superb.. dis is wat i’ve been lukin for :) many thanx :)

  • Naresh

    I’m new to the this programming just give me ur demo code files

  • Joshua

    Can you post your source code? This is exactly what I’m looking to do, but I’m still pretty new at this and it is difficult to follow your code snippets.

    Thanks