user2772060
user2772060

Reputation: 9

Using value of array element in javascript function does not work

This batch does not work, although I put in all possible checks to know wthere a certain assignment does not come through:

alert("valorsumo = "+valorsumo);  // okay
for (j = 0; j <= "<?php echo $fVN ?>"; j++) {
  horp = valornbroj[j];
  alert("horp = "+horp);  // okay
  elcentoj[j] = Math.round(horp/valorsumo * 1000) / 10;  // percentage with one decimal
  alert("percentage = "+elcentoj[i]);  //  undefined !

The queer thing is that the same kind of code, met in a separate file produces the desired answer:

function het()  {     
  var nbroj = [],
  sumo = 3894,
  elcentoj = [];
  nbroj[0] = "290046";   
  elcentoj[0] = Math.round(nbroj[0]/sumo * 1000) / 10;
  alert("percentage = "+elcentoj[0]);  // okay
}

Am I blind? Thanks in advance !

Upvotes: 0

Views: 37

Answers (1)

Tareq Salah
Tareq Salah

Reputation: 3718

In this line

alert("percentage = "+elcentoj[i]);  

I is not defined replace i with j

alert("percentage = "+elcentoj[j]);

So your loop will be like this

for (j = 0; j <= "<?php echo $fVN ?>"; j++) {
  horp = valornbroj[j];
  alert("horp = "+horp);  // okay
  elcentoj[j] = Math.round(horp/valorsumo * 1000) / 10;  // percentage with one decimal
  alert("percentage = "+elcentoj[j]);  
}

Upvotes: 2

Related Questions