0

I am stuck at this problem. I have this code (string is of the form: 'var1,var2,var3', and someIdArray is an array containing some id's):

function myFunction1(variable,string)
  {
  var myArray = string.split(',');
  for (i=0;i<myArray.length;i++)
    {
    for (j=0;j<someIdArray[j].length;j++)
      {
      document.getElementById(someIdArray[j]).onclick=function() { myFunction2(variable,myArray[i]) };
      }
    }
  }
function myFunction2(variable1,variable2)
  {
  alert(variable1);
  alert(variable2);
  }

Now when I click an element with an id in someIdArray, myFunction2 runs, and I get variable1 as I put it in myFunction1, but variable2 is undefined. How can I make sure that the onclick I defined for the element I clicked has fixed variables?

vrugtehagel
  • 1,009
  • 1
  • 9
  • 20

3 Answers3

1

Try it like this:

function myFunction1(variable,string)
{
  var myArray = string.split(',');
  for (var i=0;i<myArray.length;i++)
  {
    for (var j=0;j<someIdArray.length;j++)
    {
      document.getElementById(someIdArray[j]).onclick=function()
      {
         var localI = i;
         myFunction2(variable,myArray[localI]);
      }
    }
  }
}
function myFunction2(variable1,variable2)
{
  alert(variable1);
  alert(variable2);
}

The problem in your code is that i and j are global vars because you didn't add the var keyword to them.

So you pass a global var that gets increased to myArray.length to the function.

If you do myArray[myArray.length] you will get undefined.

What I did in the above code was store a local variable that gets encapsulated in the onClick function scope.

Another way would be this:

for (var i=0;i<myArray.length;i++)
{
    for (var j=0;j<someIdArray.length;j++)
    {
      var myArrayIElement = myArray[i];
      document.getElementById(someIdArray[j]).onclick=function()
      {

         myFunction2(variable,myArrayIElement);
      }
    }
}

Here you make a variable with the value from myArray[i] and pass it to the onClick function, instead of passing the i to the function.

Andrei
  • 3,086
  • 2
  • 19
  • 24
0

The issue is your inner for loop:

for (j=0;j<someIdArray[j].length;j++)

you probably want someIdArray.length rather than the length of the jth element

jshanley
  • 9,048
  • 2
  • 37
  • 44
0

Your corrected code here, This is a problem with scope, you have did two wrong things, 1. the someIdArray length you've got is wrong 2. Haven't assign array element and pass to the click event

function myFunction1(variable, string) {
    var myArray = string.split(',');
    for (var i = 0; i < myArray.length; i++) {
        var arrEle = myArray[i];
        for (var j = 0; j < someIdArray.length; j++) {
            document.getElementById(someIdArray[j]).onclick = function() {
                myFunction2(variable, arrEle);
            };
        }
    }
}

function myFunction2(variable1, variable2) {
    alert(variable1);
    alert(variable2);
}
SaminatorM
  • 630
  • 5
  • 18