Issue dynamically generate onclick events

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
SBukoski
Forum Contributor
Posts: 128
Joined: Wed May 21, 2003 10:39 pm
Location: Worcester, MA

Issue dynamically generate onclick events

Post 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?
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Post 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.
There are 10 types of people in this world, those who understand binary and those who don't
SBukoski
Forum Contributor
Posts: 128
Joined: Wed May 21, 2003 10:39 pm
Location: Worcester, MA

Post 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.
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Post 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 :)
There are 10 types of people in this world, those who understand binary and those who don't
Post Reply