Chained DropDown in Javascript using XML

Sample Chained HTML DropDown      
In our previous post we have learned about how to create Chained Drop-downs using javascript. In that example, the values for the 2nd drop-down were being hard-coded in the javascript itself. Though this approach is fairly easy to implement, it doen't offer a fully dynamic approach. If we need to add/delete options or update any exisitng options, then we need to alter the javascript code each time. Also a person who has less or no previous experience with Javascript may not be able to use or modify that logic.

        This problem can be solved by externalizing your data from the code, say, in form of an XML. In order to change the drop-down values you just need to add, delete or modify the values in the XML file. In this post we will discuss how to implement such a dynamic Chained DropDown using javascript.

        We will create the two drop-downs, a 'Company' drop-down which lists mobile companies and 'Model' drop-down which list out models for the selected company.
<select id="Company" >
 <option value=""></option>
 <option value="Samsung">Samsung</option>
 <option value="Apple">Apple</option>
 <option value="Nokia">Nokia</option>
</select>

<select id="Model"> </select>

        XML stands for Extensible Markup Language. It is classified as an extensible language because it allows its users to define their own tags. The XML file which has our data has a 'device' tag containing a 'name' attribute which holds the Company name. The model tag is contained inside a device tag and holds information about the Model name. Here is the content of the 'info.xml' file which holds the data for this example.
<?xml version="1.0" ?> 
<data>
    <device name="Nokia">
        <model>Lumia</model>
        <model>PureView</model>
    </device>
    <device name="Samsung">
        <model>Galaxy S2</model>
        <model>Galaxy S3</model>
    </device>
    <device name="Apple">
        <model>iPhone4</model>
        <model>iPhone5</model>
    </device>
</data>

        Now we need to import this data from the XML file. To manipulate an XML document in javascript, we need an XML parser. Today all browsers come with in-built parsers that can parse the XML document. The parser loads the document into your computer’s memory and once loaded, its data can be manipulated using the DOM(Document Object Model). We are using a cross-browser function to import the XML as there is significant difference in implementation of Microsoft Browser based XML parser and the Mozilla browsers (Firefox, Chrome, Safari) based XML parser.
/* Cross-Browser Import of XML document into a XML Document. */
function importXML(xmlfile) {
    var xmlDoc;
    if (typeof window.ActiveXObject != 'undefined') {
        //code for IE
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = false;
        xmlDoc.load(xmlfile);
        } else {
            try {
                // code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp=new XMLHttpRequest();
                xmlhttp.open("GET", xmlfile, false);
                xmlhttp.setRequestHeader('Content-Type', 'text/xml');
                xmlhttp.send();
                xmlDoc=xmlhttp.responseXML;
            } catch (Exception) {
                alert("Your browser is not supported. Try firefox !!");
            }
        }
    return xmlDoc;
}

        The loadXMLOption method retrieves the options for the model combobox from the XML file. This is to be called when user selects an option in the 'Company' drop-down. It first loads the XML file by using the 'importXML' method we have previously written. From the XML document object, we retrieve all the tags with tag name as 'device'. We then loop through each 'device' tag and check if its 'name' attribute's value is same as the one we have selected in the 'Company' drop-down. If found similar, we then retrieve all the 'model' tags under that specific 'device' tag and add each tag's node value as option to the 'Model' drop-down.
/* Get the options for the model combobox from the XML. */
function loadXMLOption() {
    // Load the xml file
    var xmlDoc=importXML("info.xml");
    xmlObj=xmlDoc.documentElement;
    // Get all Elements with Tag name 'device'
    DeviceObj = xmlObj.getElementsByTagName("device");
    for(var i=0; i < DeviceObj.length; i++) {
        // Loop through each device tag and check if its name is equal to the selected device value
        if (document.getElementById('Company').value == DeviceObj[i].getAttribute("name")) {  
            // If matching device found get the model tags under that device
            modelObj = DeviceObj[i].getElementsByTagName("model");
            document.getElementById('Model').options.length = 0;
            // Create options for the Model comboBox.
            for(var j=0; j < modelObj.length; j++) {
                var opt = document.createElement('option');
                opt.value = modelObj[j].firstChild.nodeValue;
                opt.text = modelObj[j].firstChild.nodeValue;
                document.getElementById('Model').options.add(opt);
            }
        }
    }
}
Now call this method on the onChange event of the company drop-down.
<select id="Company" onchange="loadXMLOption();">
        Thats it and now we have a truly dynamic Chained Drop-downs. You can change or add the model values in the XML file. If you want an easy way to develop chained drop-down without involving XML, you can try this post.
You can get the entire code from below. Comments and suggestions are welcome.
<html>
<head>

<script language="javascript">
/* Cross-Browser Import of XML document into a XML Document. */
function importXML(xmlfile) {
    var xmlDoc;
    if (typeof window.ActiveXObject != 'undefined') {
        //code for IE
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = false;
        xmlDoc.load(xmlfile);
        } else {
            try {
                // code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp=new XMLHttpRequest();
                xmlhttp.open("GET", xmlfile, false);
                xmlhttp.setRequestHeader('Content-Type', 'text/xml');
                xmlhttp.send();
                xmlDoc=xmlhttp.responseXML;
            } catch (Exception) {
                alert("Your browser is not supported. Try firefox !!");
            }
        }
    return xmlDoc;
}

/* Get the options for the model combobox from the XML. */
function loadXMLOption() {
    // Load the xml file
    var xmlDoc=importXML("info.xml");
    xmlObj=xmlDoc.documentElement;
    // Get all Elements with Tag name 'device'
    DeviceObj = xmlObj.getElementsByTagName("device");
    for(var i=0; i < DeviceObj.length; i++) {
        // Loop through each device tag and check if its name is equal to the selected device value
        if (document.getElementById('Company').value == DeviceObj[i].getAttribute("name")) {  
            // If matching device found get the model tags under that device
            modelObj = DeviceObj[i].getElementsByTagName("model");
            document.getElementById('Model').options.length = 0;
            // Create options for the Model comboBox.
            for(var j=0; j < modelObj.length; j++) {
                var opt = document.createElement('option');
                opt.value = modelObj[j].firstChild.nodeValue;
                opt.text = modelObj[j].firstChild.nodeValue;
                document.getElementById('Model').options.add(opt);
            }
        }
    }
}
</script>

</head>
<body>

<h2>Chained Drop-Down - using XML</h2>

Device : <select id="Company" onchange="loadXMLOption();">
  <option value=""></option> 
  <option value="Samsung">Samsung</option>
  <option value="Apple">Apple</option> 
  <option value="Nokia">Nokia</option>
</select>

Model : <select id="Model"> </select>

</body>
</html>

4 comments:

  1. the XML parser code doesnt seem to be working here..can you suggest something

    ReplyDelete
  2. it's working in firefox and IE9 but in chrome... do you know how to make it work?

    ReplyDelete
    Replies
    1. [Solved]It's not working locally, but working remotely.

      Delete
    2. open chrome with the following option to make it work locally: chrome.exe --allow-file-access-from-files

      Delete

Related Posts Plugin for WordPress, Blogger...
 

Copyright © 2012 | ScriptSplash | Powered by Blogger Templates