?
Solved

dropdown using xml javascript

Posted on 2006-04-10
16
Medium Priority
?
1,672 Views
Last Modified: 2013-11-19
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
Comment
Question by:chaitu chaitu
  • 6
  • 6
  • 3
  • +1
16 Comments
 
LVL 6

Expert Comment

by:nabsol
ID: 16424069
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
 
LVL 6

Accepted Solution

by:
nabsol earned 1200 total points
ID: 16424176
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
 
LVL 20

Author Comment

by:chaitu chaitu
ID: 16424184
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 6

Expert Comment

by:nabsol
ID: 16424197
Hi
I have posted whole solution abve :) just 1 minute difference

By Nab
0
 
LVL 20

Author Comment

by:chaitu chaitu
ID: 16424198
how to clear the cities before selecting another country
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 16424219
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
 
LVL 20

Author Comment

by:chaitu chaitu
ID: 16424228
ok got it
0
 
LVL 20

Author Comment

by:chaitu chaitu
ID: 16424249
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
 
LVL 6

Expert Comment

by:nabsol
ID: 16424253
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
 
LVL 6

Expert Comment

by:nabsol
ID: 16424315
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
 
LVL 63

Assisted Solution

by:Zvonko
Zvonko earned 800 total points
ID: 16425116
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
 
LVL 20

Author Comment

by:chaitu chaitu
ID: 16425949
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
 
LVL 6

Expert Comment

by:nabsol
ID: 16426062
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
 
LVL 63

Expert Comment

by:Zvonko
ID: 16426238
Did you notice my posting?
0
 
LVL 20

Author Comment

by:chaitu chaitu
ID: 16426662
very good one..

how can u change this one document.forms[0].country.onchange(); to attachEvent function??
0
 
LVL 63

Expert Comment

by:Zvonko
ID: 16426702
???
I do not understand the question.
attachEvent() is assigning the event handler, and onchange() is firing the event handler.

0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Styling your websites can become very complex. Here I'll show how SASS can help you better organize, maintain and reuse your CSS code.
A while back, I ran into a situation where I was trying to use the calculated columns feature in SharePoint 2013 to do some simple math using values in two lists. Between certain data types not being accessible, and also with trying to make a one to…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
HTML5 has deprecated a few of the older ways of showing media as well as offering up a new way to create games and animations. Audio, video, and canvas are just a few of the adjustments made between XHTML and HTML5. As we learned in our last micr…
Suggested Courses

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question