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+')', '', '')};

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Well done. I missed that because I didn't understand the term in the title closure. It works great.
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"));

3 Comments

Thanks, but I try to avoid jQuery where possible, especially wnen in loops, because of the over-head. Interesting alternative though.
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).
The answer I accepted worked fine. The solution was quite well described on the post linked to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.