Using jQuery and XML to Populate a Drop-Down Box

Source Demo Reading XML with jQuery Source

You’ll now have an index.html file that looks like this:




	
	
	
	Using jQuery and XML to populate a drop-down box demo
        


Next you’ll need a simple XML file to load.

Here is the one that I used : dropdown.xml



	
    	first set
 		
 			option a
 			option b
 		
 	
   	
    	second set
 		
 			option 1
 			option 2
 		
 	
 	
    	third set
 		
 			option 1a
 			option 2b
 		
 	
 

Now that you’ve created your XML, add a form with a select box to the HTML page. I simply replaced everything within the body tag from our index.html from the previous article.

Once the XML is ready, jump back into the index.html file. You’ll need to update the jQuery Ajax call to get the new XML document. To do this, simply change the url to your new document.

old:

$.ajax({
        type: "GET",
	url: "sites.xml",
	dataType: "xml",
	success: function(xml) {

	}
});

new:

$.ajax({
        type: "GET",
	url: "dropdown.xml",
	dataType: "xml",
	success: function(xml) {

	}
});

With the Ajax call in place, you need to tell it what to do when it loads the XML in the success function. Start by getting the select tag with jQuery and storing it in a variable for later use. The select tag you are looking for has an id of mySelect.

var select = $('#mySelect');

Next, loop through all of the menuitem nodes in the XML with a jQuery each function.

$(xml).find('menuitem').each(function(){
});

Inside the each function, you will get the title of your menuitem. Create an option tag as a header for the menuitem, and then create another jQuery each function to get all the possible values that go with the current menuitem.

The first thing you’ll want to do within the each function for the menuitem is get the title and append it to your select.

var title = $(this).find('title').text();
select.append("");

There is a empty option tag in the code to get a space above the header, that way the drop down will be easier for the user to read. Add a class of ddheader to the option tag so in browser like firefox you can make the header bold.

With the header now inserted into the select, you’ll now need to create the options that will be under that header. To do this, use another jQuery each function, looking for all the value nodes that are in the menuitem node. Within this each you will get the text in the value node and then append it to the select tag as an option with a class of ddindent. The ddindent class is used to push these items to the right a bit so they are easy to follow.

$(this).find('value').each(function(){
	var value = $(this).text();
	select.append("");
});

That is just about everything, there’s only one more thing. At the end of the success function, change the option tag you hard coded in the index.html file that said “loading” to now say “please make a selection.” Make sure that it’s selected to start with by giving it the selected attribute. Because the option tag is the first child of the select tag, you can use the children function with the optional parameter of “:first”. This will return only the first child of the select tag.

select.children(":first").text("please make a selection").attr("selected",true);

You should now have a functional drop-down box loaded with XML via jQuery.

Source Demo Reading XML with jQuery Source

13 Comments

  1. Jake Scott on March 11, 2009 at 5:12 am

    Hey Nice site and cool ideas to blog about. Perhaps you could expand on your jquery + xml articles and show us how to deal with xml namespaces. For example Adobe Kuler rss feed has xml tags like which make selecting elements harder because you have to escape the : character. Like this $(xml).find(‘kuler\\:swatch’) or something?

    Cheers
    Jake



  2. khautinh on March 12, 2009 at 7:20 pm

    This helps me a lot. How do I select data from drop down box 1 and populate the data to the drop down box 2? Any samples would be appreciated.



  3. Blog Roll II | Buanzolandia on March 13, 2009 at 9:41 am

    […] Using jQuery and XML to Populate a Drop-Down Box También en inglés, pero con mucho código, pero enseña a usar dataType: “xml” en peticiones ajax con jQuery e iterando con each … y si te quedaste con ganas de más sobre XML y jQuery … Reading XML with jQuery Como leer xml con jQuery desde cero. […]



  4. links for 2009-03-14 « pabloidz on March 14, 2009 at 7:01 am

    […] Using jQuery and XML to Populate a Drop-Down Box Think2Loud (tags: jquery) Blogroll […]



  5. Blog Roll II | Buanzolandia on March 15, 2009 at 1:45 am

    […] Inglés sobre las funciones anonimas, no siempre muy útil pero potente en determinados problemas Using jQuery and XML to Populate a Drop-Down Box También en inglés, pero con mucho código, pero enseña a usar dataType: “xml” en peticiones […]



  6. Eric on March 27, 2009 at 3:05 am

    Anyway it won’t work for IE. Can you provide an alternative solution for IE?



  7. Anthony on April 1, 2009 at 8:39 am

    This is a great solution, but as Eric mentioned, it does not work on IE or more specifically IE6 (The devils spawn). :-)
    There are still a lot of people with IE6 out there, and It would be great if this were cross browser compatible. So far it works for IE7 and above and Fire fox. I haven’t checked other browsers yet.



  8. Justin on May 13, 2009 at 5:44 pm

    Fix for IE:

    var DataUtilities = (function() {

    //Privileged variables and methods
    var self = {
    “processXML”: function(xml) {
    if (!jQuery.support.htmlSerialize) {
    //If IE 6+
    var xmlDoc = new ActiveXObject(“Microsoft.XMLDOM”);
    xmlDoc.loadXML(xml);
    xml = xmlDoc;
    }
    return xml;
    }
    };
    return self;
    })();

    then just do this:

    xml = DataUtilities.processXML(xml);



  9. Michael on May 31, 2009 at 2:11 pm

    …But making things browser specific is what we’re trying to avoid: it’s the 90’s all over again! So for small datapackages, i’ll use json.



  10. bobin on August 3, 2009 at 11:37 am

    hey ,

    thanks for the solution , by the way the links to the demo and the source are not working could you please check??



    • josh on August 4, 2009 at 3:41 am

      Thanks for the tip. Got that fixed now.



  11. Shobhit on October 30, 2009 at 8:38 am

    Thanks dude.Really good and simple script……….