Click to See Complete Forum and Search --> : [RESOLVED] array loop in javascript halts on no data.


d4rg0
01-06-2007, 12:54 PM
I have some trouble with an array loop in javascript.

First som background :

The content of http.responseXML is :
<data><navn>$navn</navn><pris>$pris</pris><kategori>$kategori</kategori><msg>$msg</msg></data>;

The values of my array "noder" is the same as some document id tags of form input boxes in my html document.

And I can confirm that the FOR loop is working, as it outputs an alert box with both the array value and corresponding xml value from the http.reponseXML if I run a test. So, both vhnode and vhtemp has valid data.

This works, as long as every php variable in http.responseXML is set to a value.


var xmlDocument = http.responseXML;
var noder = new Array('navn','pris','kategori','msg');
var x=0;
for (x=0; x<4; x++) {
var vhnode = noder[x];
var vhncount = xmlDocument.getElementsByTagName(vhnode).item(0).firstChild.data;
if (vhncount != "") {
var vhtemp = xmlDocument.getElementsByTagName(vhnode).item(0).firstChild.data;
document.getElementById(vhnode).value = vhtemp;
} else {
var vhtemp = " ";
document.getElementById(vhnode).value = vhtemp;
}
}



So, my problems :

The trouble is that the $msg variable is not always set. The IF (vhncount != "") seems to catch this, but the code halts at that stage, not going into the else statement.

Instead it gives me the following error :
xmlDocument.getElementsByTagName(vhnode).item(0).firstChild has no properties

I guess the problem is that the variable vhncount can't be set as the xmlDocument.getElementsByTagName(vhnode).item(0).firstChild.data is empty.

So, how do I check if the xmlDocument.....firstChild.data is empty and get into my ELSE statement?

d4rg0
01-06-2007, 05:12 PM
Solved using this :

if (xmlDocument.getElementsByTagName(vhnode).item(0).firstChild) {

as a replacement for this two lines in the original code:

var vhncount = mlDocument.getElementsByTagName(vhnode).item(0).firstChild.data;
if (vhncount != "") {