passing an Array in javascript

Hi,

I am simply trying to pass an array from one javascript function to another when the tinyPlusSubrowImage is clicked.

The variables in the array are elements, but I would also like to pass strings at the same time in the array.

I am seeing the following error in firebug:

missing ] after element list
 test([object HTMLTableRowElement],[object HTMLTableElement])

I *think* I am passing by reference as I should be. Can anyone see what I am doing wrong ?

Thanks
P.S I notice that the plus signs are getting stripped out of my function first in the code box. I am putting two pluses, one to either side of array on the tinyPlusSubrowImage line

function second(array){
  alert(array);
} 
 
function first(outerRow, outerTable){
var array = new Array();
         array[0] = outerRow;
         array[1] = outerTable;
         tinyPlusSubrowImage.setAttribute('onclick','second(' + array + ')');
}

Open in new window

COMPSUPPAsked:
Who is Participating?
 
David S.Connect With a Mentor Commented:
Nope. The argument for the anonymous function won't be passed until the event is triggered, in which case the only variable to be passed to it (if any) would be the event object.

You could write it like the following code, but doing so is only needed when inside a loop. (I used two different variable names for clarity. In practice I'd use the same name.) This is called "closures", by the way.
tinyPlusSubrowImage.onclick = (function(myArray){
  function(){ second(myArray); };
})(array);

Open in new window

0
 
Samuel LiewCommented:
You cannot do that because setting the attribute is by a string. You cannot put an object into the onclick attribute. What you should do is to pass the ID of the objects.

If you need further help kindly post your page code here, or a link to it so we can take a look.
0
 
BadotzCommented:
Have you tried this:


tinyPlusSubrowImage.onclick = second(array);

Open in new window

0
 
David S.Commented:
Badotz, that will call the function right way. The way to get around that is to put it inside an anonymous function:

P.S. It's best to avoid setting event handlers with setAttribute().
tinyPlusSubrowImage.onclick = function(){ second(array); };

Open in new window

0
 
BadotzCommented:
Kravimir: Of course, you are right. I must have still been asleep when I posted that :=/

But shouldn't it really be:


tinyPlusSubrowImage.onclick = function(array){ second(array); };

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.