• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1688
  • Last Modified:

dropdown using xml javascript

i have below xml file ;when the page loads in one drop down box i have all country names should  be displayed and when i select country name corresponding city names should be displayed .first of all how to read the country values in drop down box and where to write the onchange function in xml file.

function importXML()
{
      if (document.implementation && document.implementation.createDocument)
      {
            xmlDoc = document.implementation.createDocument("", "", null);
            xmlDoc.onload = createTable;
      }
      else if (window.ActiveXObject)
      {
            xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.onreadystatechange = function () {
                  if (xmlDoc.readyState == 4) createTable()
            };
       }
      else
      {
            alert('Your browser can\'t handle this script');
            return;
      }
      xmlDoc.load("Countries.xml");
}


<Countries>
      <Country id="INDIA">
            <city>Delhi</city>
            <city>Mumbai</city>
            <city>Chcnnai</city>
      </Country>
      <Country id="AUSTRALIA">
            <city>Sydney</city>
            <city>Melbourne</city>
            <city>Perth</city>
      </Country>
      <Country id="ENGLAND">
            <city>London</city>
            <city>Manchester</city>
            <city>Durham</city>
      </Country>
</Countries>
0
chaitu chaitu
Asked:
chaitu chaitu
  • 6
  • 6
  • 3
  • +1
2 Solutions
 
nabsolCommented:
Hi

First thing how to read these country names in drop down box..

no_of_countries = xmldoc.getElementsByTagName("Country").length;  // get tag country length
   
   for (i = 1; i <= no_of_countries; i++)
   {
      country_name = xmldoc.getElementsByTagName("Country")[i-1].attributes.getNamedItem("Id").value;
      //you can add here to your drop down of countries like
      document.forms[0].countries.options[document.forms[0].countries.options.length] = new Option(country_name, i-1);
   }

Second thing you will not be writting function in xml file. You just create and html file and you can write above javascript there in body and you will write code in header of onchange()

If you need further help let me know
0
 
nabsolCommented:
Hi

Hope this helps
put your xml into a file c.xml and in same directory put and html file having this code

<html>
<head>
<script language="JavaScript">

var xmlDoc
function loadXML()
{
//load xml file
// code for IE
if (window.ActiveXObject)
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.load("c.xml");
createTable()
}
// code for Mozilla, etc.
else if (document.implementation &&
document.implementation.createDocument)
{
xmlDoc= document.implementation.createDocument("","",null);
xmlDoc.load("c.xml");
xmlDoc.onload=createTable
}
else
{
alert('Your browser cannot handle this script');
}
}

function createTable()
{

   no_of_countries = xmlDoc.getElementsByTagName("Country").length;  // get tag country length
   for (i = 1; i <= no_of_countries; i++)
   {
      country_name = xmlDoc.getElementsByTagName("Country")[i-1].attributes.getNamedItem("id").value;
      //you can add here to your drop down of countries like
      document.forms[0].countries.options[document.forms[0].countries.options.length] = new Option(country_name, i-1);
   }
}

function showCity()
{
  useform = document.forms[0]
  selected_country_no = useform.countries.options[useform.countries.selectedIndex].value;
  if (selected_country_no != -1)
  {
    selected_country = xmlDoc.documentElement.childNodes[selected_country_no].attributes[0].value

    table_city = xmlDoc.documentElement.childNodes[selected_country_no].childNodes

    for (i=0; i < table_city.length; i++)
    {
      document.forms[0].cities.options[document.forms[0].cities.options.length] = new Option(table_city[i].text, i-1);
    }
  }
}
</script>
</head>

<body onload="loadXML()">

<form>
<select name="countries" onchange="javascript:showCity(this)" \>
  <option value="-1">Select Country</option>
</select>

<select name="cities" >
  <option value="-1">Select city</option>
</select>

</form>
</body>
</html>

I hope it will work

By Nab
0
 
chaitu chaituAuthor Commented:
how to get the cities of corresponding countries

function getCity()
{

   for (i = 1; i <= 3; i++)
   {
      city_name = xmlDoc.getElementsByTagName("city")[i-1].childNodes[0].value;
        alert(city_name)
      document.forms[0].cities.options[document.forms[0].cities.options.length] = new Option(city_name, i-1);
   }


}
</script>
</head>
<body onload="importXML()">
<form name="frm">
<select name="countries" onChange="getCity()">
</select>
<select name="cities">
</select>
0
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

 
nabsolCommented:
Hi
I have posted whole solution abve :) just 1 minute difference

By Nab
0
 
chaitu chaituAuthor Commented:
how to clear the cities before selecting another country
0
 
Michel PlungjanIT ExpertCommented:
Nabsol, why the strange contruct?

 for (i = 1; i <= no_of_countries; i++)
   {
      country_name = xmldoc.getElementsByTagName("Country")[i-1]

instead of the more logical and less error prone

 for (i = 0; i < no_of_countries; i++)
   {
      country_name = xmldoc.getElementsByTagName("Country")[i]


0
 
chaitu chaituAuthor Commented:
ok got it
0
 
chaitu chaituAuthor Commented:
instead of writing below code in html

<select name="countries" onChange="getCity()">
</select>
<select name="cities">
</select>


i want to write it in javascript and want to add onChange event to it;

0
 
nabsolCommented:
Hi

This is more appropriate:

<html>
<head>
<script language="JavaScript">

var xmlDoc
function loadXML()
{
//load xml file
// code for IE
if (window.ActiveXObject)
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.load("c.xml");
createTable()
}
// code for Mozilla, etc.
else if (document.implementation &&
document.implementation.createDocument)
{
xmlDoc= document.implementation.createDocument("","",null);
xmlDoc.load("c.xml");
xmlDoc.onload=createTable
}
else
{
alert('Your browser cannot handle this script');
}
}

function createTable()
{

   no_of_countries = xmlDoc.getElementsByTagName("Country").length;  // get tag country length
   for (i = 1; i <= no_of_countries; i++)
   {
      country_name = xmlDoc.getElementsByTagName("Country")[i-1].attributes.getNamedItem("id").value;
      //you can add here to your drop down of countries like
      document.forms[0].countries.options[document.forms[0].countries.options.length] = new Option(country_name, i-1);
   }
}

function showCity()
{
  useform = document.forms[0]
  selected_country_no = useform.countries.options[useform.countries.selectedIndex].value;
  if (selected_country_no != -1)
  {
    selected_country = xmlDoc.documentElement.childNodes[selected_country_no].attributes[0].value

    table_city = xmlDoc.documentElement.childNodes[selected_country_no].childNodes
 
    myopts = ""
    for (i=0; i < table_city.length; i++)
    {
      a = i-1
      myopts += "<option value='"+a+"'>"+ table_city[i].text+"</option>";
    }
       document.getElementById("mycities").innerHTML = "<select name='cities' > <option value='-1'>Select city</option>"+myopts+"</selet>"    
  }
 
}
</script>
</head>

<body onload="loadXML()">

<form>
<select name="countries" onchange="javascript:showCity(this)" \>
  <option value="-1">Select Country</option>
</select>

<div id="mycities">
</div>

</form>
</body>
</html>

By Nab
0
 
nabsolCommented:
Hi
Is this what you want:

<html>
<head>
<script language="JavaScript">

var xmlDoc
function loadXML()
{
//load xml file
// code for IE
if (window.ActiveXObject)
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.load("c.xml");
createTable()
}
// code for Mozilla, etc.
else if (document.implementation &&
document.implementation.createDocument)
{
xmlDoc= document.implementation.createDocument("","",null);
xmlDoc.load("c.xml");
xmlDoc.onload=createTable
}
else
{
alert('Your browser cannot handle this script');
}
}

function createTable()
{
   myopts = ""
   no_of_countries = xmlDoc.getElementsByTagName("Country").length;  // get tag country length
   for (i = 1; i <= no_of_countries; i++)
   {
      country_name = xmlDoc.getElementsByTagName("Country")[i-1].attributes.getNamedItem("id").value;
      //you can add here to your drop down of countries like
      a = i-1
      myopts += "<option value='"+a+"'>"+country_name+"</option>";
   }
   document.getElementById("mycountries").innerHTML = "<select name='countries' onchange='showCity(this)'> <option value='-1'>Select city</option>"+myopts+"</selet>"    
}

function showCity(gotCountries)
{
  useform = document.forms[0]
  selected_country_no = useform.countries.options[useform.countries.selectedIndex].value;

  if (selected_country_no != -1)
  {
    selected_country = xmlDoc.documentElement.childNodes[selected_country_no].attributes[0].value

    table_city = xmlDoc.documentElement.childNodes[selected_country_no].childNodes
 
    myopts = ""
    for (i=0; i < table_city.length; i++)
    {
      a = i-1
      myopts += "<option value='"+a+"'>"+ table_city[i].text+"</option>";
    }
       document.getElementById("mycities").innerHTML = "<select name='cities' ><option value='-1'>Select city</option>"+myopts+"</selet>"    
  }
 
}
</script>
</head>

<body onload="loadXML()">

<form>

<div id="mycountries">
</div>

<div id="mycities">
</div>

</form>
</body>
</html>


By Nab
0
 
ZvonkoSystems architectCommented:
Made by Zvonko ;-)

<html>
<head>
<title>Zvonko &#42:</title>
<script>
var cTab = new Array();
function createTable(){
  var theList = document.getElementById("countList");
  theList = theList.getElementsByTagName("Countries")[0].childNodes;
  for(var i=0;i<theList.length;i++){
    var ctry = theList[i].getAttribute("id");
    cTab[ctry] = new Array();
    var ctys = theList[i].getElementsByTagName("city")
    for(var j=0;j<ctys.length;j++){
      cTab[ctry][j] = ctys[j].childNodes[0].nodeValue;
    }
  }
  var opt = document.forms[0].country.options;
  for(c in cTab){
    opt[opt.length] = new Option(c,c);
  }
  document.forms[0].country.onchange();
}
function getCities(theSel){
  var opt = theSel.form.city.options;
  var val = cTab[theSel.value];
  opt.length=0;
  for(var i=0;i<val.length;i++){
    opt[i] = new Option(val[i],val[i]);
  }
}
</script>
</head>
<body onLoad="createTable()">
<form>
<select name="country" onChange="getCities(this)">
</select>
<select name="city">
</select>
</form>
</body>
<xml id="countList" src="Countries.xml">
</xml>
</html>

0
 
chaitu chaituAuthor Commented:
i changed little bit;may be written some extra code in it;try to remove that code if anybody finds;

<html>
<head>
<script>
function importXML()
{
      if (document.implementation && document.implementation.createDocument)
      {
            xmlDoc = document.implementation.createDocument("", "", null);
            xmlDoc.onload = createTable;
      }
      else if (window.ActiveXObject)
      {
            xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.onreadystatechange = function () {
                  if (xmlDoc.readyState == 4) createTable()
            };
       }
      else
      {
            alert('Your browser can\'t handle this script');
            return;
      }
      xmlDoc.load("country.xml");
}

function createTable()
{
      no_of_countries = xmlDoc.getElementsByTagName("Country").length;  

      var tab            = document.getElementById("tab");
      var tbody      = document.createElement("tbody");
      var tr            = document.createElement("tr");
      var td            = document.createElement("td");
      
              myElement=document.createElement("select");
            myElement.setAttribute("name","countries");
            myElement.setAttribute("id","countries");

      


   for (i = 0; i < no_of_countries; i++)
   {
      country_name = xmlDoc.getElementsByTagName("Country")[i].attributes.getNamedItem("id").value;

            myElement.appendChild(addOption(country_name,country_name));


   }
            myElement.attachEvent("onchange",eventHandler);

      td.appendChild(myElement);

      tr.appendChild(td);
      tbody.appendChild(tr);
      tab.appendChild(tbody);

      getCity();
}


function addOption(optionStr,optionValue)
{
      var myOption=document.createElement("option");
      myOption.setAttribute("innerText",optionStr);
      if(optionValue!=null && optionValue!="")
            myOption.setAttribute("value",optionValue);
      else
            myOption.setAttribute("value",optionStr);
      myOption.text=optionStr;
      return myOption;
}
function getonChangeCity()
{
        
       selected_country_no=document.getElementById("countries").selectedIndex;

    document.getElementById('cities').options.length = 0;

        if (selected_country_no != -1)
        {
            table_city = xmlDoc.documentElement.childNodes[selected_country_no].childNodes;


            for (i=0; i < table_city.length; i++)
            {

             myElement.appendChild(addOption(table_city[i].text,table_city[i].text));

            }

        }

      


}


function getCity()
{
           var tab            = document.getElementById("tab");
            var tbody      = document.createElement("tbody");
            var tr            = document.createElement("tr");
            var td            = document.createElement("td");
      
              myElement=document.createElement("select");
            myElement.setAttribute("name","cities");
            myElement.setAttribute("id","cities");


        selected_country_no=document.getElementById("countries").selectedIndex;

        if (selected_country_no != -1)
        {
            table_city = xmlDoc.documentElement.childNodes[selected_country_no].childNodes;


            for (i=0; i < table_city.length; i++)
            {

             myElement.appendChild(addOption(table_city[i].text,table_city[i].text));

            }

        }

      td.appendChild(myElement);

      tr.appendChild(td);
      tbody.appendChild(tr);
      tab.appendChild(tbody);


}

function eventHandler()
{
      getonChangeCity();
      return;
}
</script>
</head>
<body onload="importXML()">
<form name="frm">
      <table id="tab" width="760"  border=0 cellspacing="1" cellpadding="2">
      </table>
</form>
</html>
0
 
nabsolCommented:
Hi

Can't remove much. :)

<html>
<head>
<script>
function importXML()
{
     if (document.implementation && document.implementation.createDocument)
     {
          xmlDoc = document.implementation.createDocument("", "", null);
          xmlDoc.onload = createTable;
     }
     else if (window.ActiveXObject)
     {
          xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
          xmlDoc.onreadystatechange = function () {
               if (xmlDoc.readyState == 4) createTable()
          };
      }
     else
     {
          alert('Your browser can\'t handle this script');
          return;
     }
     xmlDoc.load("country.xml");
}

function createTable()
{
   no_of_countries = xmlDoc.getElementsByTagName("Country").length;  

   var tab      = document.getElementById("tab");
   var tbody    = document.createElement("tbody");
   var tr       = document.createElement("tr");
   var td       = document.createElement("td");
     
   myElement=document.createElement("select");
   myElement.setAttribute("name","countries");
   myElement.setAttribute("id","countries");

   for (i = 0; i < no_of_countries; i++)
   {
      country_name = xmlDoc.getElementsByTagName("Country")[i].attributes.getNamedItem("id").value;
      myElement.appendChild(addOption(country_name,country_name));

   }
   myElement.attachEvent("onchange",eventHandler);
   td.appendChild(myElement);
   tr.appendChild(td);
   tbody.appendChild(tr);
   tab.appendChild(tbody);

   getCity();
}


function addOption(optionStr,optionValue)
{
     var myOption=document.createElement("option");
     myOption.setAttribute("innerText",optionStr);
     if(optionValue!=null && optionValue!="")
          myOption.setAttribute("value",optionValue);
     else
          myOption.setAttribute("value",optionStr);
     myOption.text=optionStr;
     return myOption;
}
function getonChangeCity()
{
       
    selected_country_no=document.getElementById("countries").selectedIndex;
    document.getElementById('cities').options.length = 0;

     table_city = xmlDoc.documentElement.childNodes[selected_country_no].childNodes;
     for (i=0; i < table_city.length; i++)
     {
        myElement.appendChild(addOption(table_city[i].text,table_city[i].text));
     }
}

function getCity()
{
          var tab       = document.getElementById("tab");
          var tbody     = document.createElement("tbody");
          var tr        = document.createElement("tr");
          var td        = document.createElement("td");
   
          myElement=document.createElement("select");
          myElement.setAttribute("name","cities");
          myElement.setAttribute("id","cities");


       selected_country_no=document.getElementById("countries").selectedIndex;
       table_city = xmlDoc.documentElement.childNodes[selected_country_no].childNodes;
       for (i=0; i < table_city.length; i++)
       {
           myElement.appendChild(addOption(table_city[i].text,table_city[i].text));

       }

     td.appendChild(myElement);
     tr.appendChild(td);
     tbody.appendChild(tr);
     tab.appendChild(tbody);
}

function eventHandler()
{
   getonChangeCity();
   return;
}
</script>
</head>
<body onload="importXML()">
<form name="frm">
     <table id="tab" width="760"  border=0 cellspacing="1" cellpadding="2">
     </table>
</form>
</html>

By Nab
0
 
ZvonkoSystems architectCommented:
Did you notice my posting?
0
 
chaitu chaituAuthor Commented:
very good one..

how can u change this one document.forms[0].country.onchange(); to attachEvent function??
0
 
ZvonkoSystems architectCommented:
???
I do not understand the question.
attachEvent() is assigning the event handler, and onchange() is firing the event handler.

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 6
  • 6
  • 3
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now