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>
LVL 20
chaitu chaituAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
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>
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

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

By Nab
chaitu chaituAuthor Commented:
how to clear the cities before selecting another country
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]


chaitu chaituAuthor Commented:
ok got it
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;

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
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
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>

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>
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
ZvonkoSystems architectCommented:
Did you notice my posting?
chaitu chaituAuthor Commented:
very good one..

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

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Web Languages and Standards

From novice to tech pro — start learning today.