Page 1 of 1

Issue dynamically generate onclick events

Posted: Wed Dec 05, 2007 10:20 pm
by SBukoski
Ok, so I'm dynamically generating rows and am including an onclick event to each row created. The code is as follows (snippet anyways):

Code: Select all

for (var a=1; a<=intQty; a++) 
{
	...
	var eqRow = document.getElementById('tblEquipment').insertRow(a);
	eqRow.onclick = function() { changeColor(eqRow, a, 'rgb(240,234,194)', 'rgb(194,209,240)'); };
	...
}
If I create one row at a time, the 'a' parameter in the function is ok. However, if I loop multiple times, let's say 3 times, the 'a' parameter will always be 3 for each row created. I would expect it to be 1 for the 1st, 2 for the 2nd and 3 for the 3rd.

Does anyone know what I am doing wrong?

Posted: Thu Dec 06, 2007 5:49 am
by VladSun
Maybe not the best solution but at least it works :)

Code: Select all

eqRow.onclick = new Function("alert(" + a + ")");
This way the "code" es evaluated at assigning time, not at the time of event.

Posted: Thu Dec 06, 2007 8:41 am
by SBukoski
Well, I tried the following, and unfortunately it didn't work. For some reason it stopped execution of the code.

Code: Select all

eqRow.onclick = new Function( "changeColor(" + eqRow + ", " + newRow + ", 'rgb(240,234,194)', 'rgb(194,209,240)');" );
However, I did some digging around the net and found that this works...

Code: Select all

function addOnClick(obj, n)
{
	obj.onclick = function() { changeColor(obj, n, 'rgb(240,234,194)', 'rgb(194,209,240)'); };
}

...

addOnClick(eqRow, newRow);
I don't really understand the reason behind WHY this works, but it does.

Posted: Thu Dec 06, 2007 11:27 am
by VladSun
The first code snippet can't work because you are trying to pass eqRow as string (you have string concatenation there).
I think that the second code lines work, because this way you've solved the "scope" problem you had had. It is the "pass by value" which solves this problem - you use a copy of the variable, not the variable itself, so any changes to this variable are not applied in your onclick function.

But maybe I am wrong - I don't know :)