0

I'm building a table in JavaScript and it contains a cell with a link in it, which when clicked, should fire a function. The cell is being added in a loop, in which i is incremented with each cycle and I want embed i in my function as a parameter.

Using the code below, when I alert(i); in the receiving function, I'm not getting the correct number. For one thing, elements added regardless of the iteration, all have the number 3 (probably not co-incidentally, I am testing this on a 3 record data-source).

The code

// Add supplier name to cell as a link
var a = document.createElement('a');
var linkText = document.createTextNode(data[i].supName);
a.appendChild(linkText);
a.title = "Click to create a purchase order.";
a.href = "#";
alert('inserting '+i); // diagnostic line
a.onclick = function(){postData ('main/createPO.php', '', 'makePO(resp,'+i+')', '', '')};
td1.appendChild(a);
tr.appendChild(td1);

The above is in a for loop where the i is incremented.

The diagnostic alert, fires:

inserting 0
inserting 1
inserting 2

... but the embedded i always seems to be 3!

This is the important line:

a.onclick = function(){postData ('main/createPO.php', '', 'makePO(resp,'+i+')', '', '')};
Peter White
  • 1,016
  • 2
  • 14
  • 29

2 Answers2

1

This person had the same problem as you, and there's a good answer for it: JavaScript closure inside loops – simple practical example

Community
  • 1
  • 1
crimson_penguin
  • 2,728
  • 1
  • 17
  • 24
1

There's an easier way to get around your issue. I had a more complicated version of this problem.

for each element, just make a custom attribute.

$(a).attr("myValue", i);

Then on .click, just pass Number($(this).attr("myValue"));

Shazboticus S Shazbot
  • 1,289
  • 2
  • 16
  • 27
  • Thanks, but I try to avoid jQuery where possible, especially wnen in loops, because of the over-head. Interesting alternative though. – Peter White Apr 02 '13 at 23:27
  • I don't know off the top of my head how to do the equivalent without jQuery, but I'm positive there's a way to do this do custom attributes with simple JS (it might not be as simple as a.myValue = i, but it should be something like that). – Shazboticus S Shazbot Apr 02 '13 at 23:29
  • The answer I accepted worked fine. The solution was quite well described on the post linked to. – Peter White Apr 02 '13 at 23:31