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