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
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.
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
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.
[…] 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. […]
[…] Using jQuery and XML to Populate a Drop-Down Box Think2Loud (tags: jquery) Blogroll […]
[…] 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 […]
Anyway it won’t work for IE. Can you provide an alternative solution for IE?
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.
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);
…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.
hey ,
thanks for the solution , by the way the links to the demo and the source are not working could you please check??
Thanks for the tip. Got that fixed now.
Thanks dude.Really good and simple script……….