views:

66

answers:

1

Hi,

I'm new to AJAX and XML. I'm stuck on a school assignment.. The task is to process an XML file consisting of 2000 different places with name, name of city and name of county. and making a dropdown menu with the different counties, but only once.

The XML file looks like this:

<places>
 <place>
  <Name>Vestby</Name>
  <City>Vestby</City>
  <County>Akershus</County>
 </place> 
...
 <place>
  <Name>Eidsbugarden</Name>
  <City>Vang</City>
  <County>Oppland</County>
 </place>
</places>

My function looks like this:

function fillElementWithCounty(){
 var selectElement = document.getElementById("selectMenu");
 var allPlaces = countyXHRobject.responseXML.getElementsByTagName("place");
 var prevCounty = "";

 selectElement.options[0] = new Option("Choose county...", "chooseCounty", true, false);
 for (teller=1; teller < allPlaces.length; teller++){
  var county = allPlaces[teller].getElementsByTagName("county")[0].firstChild.nodeValue;
   if (county ! = prevCounty ) {
    selectElement.options[teller]  = new Option(county, county, false, false);
   }
   prevCounty = county;
 }
}

This function show each county once, but it also show all "blank" counties. What do I do wrong?

The function that calls fillElementWithCounty() looks like this:

function showPlaces(){
 countyXHRobject = lagXHRobjekt();
 if (countyXHRobject) {
  countyXHRobject.onreadystatechange = function() {
   if (countyXHRobject.readyState = = 4) {
    fillElementWithCounty();
   }
  }
  countyXHRobject.open("GET", "viktigestader.xml");
  countyXHRobject.send(null);
 }
}
A: 

I got this working:

function fillElementWithCounty(){
    var selectElement = document.getElementById("selectMenu");
    var allPlaces = countyXHRobject.responseXML.getElementsByTagName("place");
    var x = countyXHRobject.responseXML;
    var prevCounty = "";

    selectElement.options[0] = new Option("Select county...", "selectcounty", true, false);
    j = 1;
    for (i=1; i < allPlaces.length; i++){
        var county = allPlaces[i].getElementsByTagName("county")[0].firstChild.nodeValue;
        if (county != prevCounty) {
            selectElement.options[j] = new Option(county, county, false, false);
            j++;
        }
        prevCounty = county;
    }
}
guzh