Expand|Select|Wrap|Line Numbers
- <mobiles>
- <brand name="Nokia">
- <model>Lumia 720</model>
- <price>Rs. 27,600</price>
- <model>Lumia 510</model>
- <price>Rs. 15,300</price>
- <model>Asha 303</model>
- <price>Rs. 12,900</price>
- <model>X2 05</model>
- <price>Rs. 5,550</price>
- </brand>
- <brand name="Samsung">
- <model>Galaxy Mega 5.8</model>
- <price>Rs. 42,000</price>
- <model>S5610</model>
- <price>Rs. 10,000</price>
- <model>E1207</model>
- <price>Rs. 2,000</price>
- <model>E1205</model>
- <price>Rs. 1,700</price>
- </brand>
- <brand name="Sony">
- <model>Xperia ZL</model>
- <price>48,000</price>
- <model>Xperia J</model>
- <price>Rs. 18,000</price>
- <model>Xperia miro</model>
- <price>Rs. 16,000</price>
- <model>Xperia Tipo Dual</model>
- <price>Rs. 12,000</price>
- </brand>
- </mobiles>
I have fetch the data in 2 combo-boxes from XML file and code looks like;
Expand|Select|Wrap|Line Numbers
- <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("mobiles.xml");
- xmlObj=xmlDoc.documentElement;
- // Get all Elements with Tag name 'brand'
- BrandObj = xmlObj.getElementsByTagName("brand");
- for(var i=0; i < BrandObj.length; i++) {
- // Loop through each brand tag and check if its name is equal to the selected brand value
- if (document.getElementById('Company').value == BrandObj[i].getAttribute("name")) {
- // If matching brand found get the model tags under that brand
- modelObj = BrandObj[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>
- Brand : <select id="Company" onchange="loadXMLOption();">
- <option value=""></option>
- <option value="Nokia">Nokia</option>
- <option value="Samsung">Samsung</option>
- <option value="Sony">Sony</option>
- </select>
- Model : <select id="Model"> </select>
- </body></html>