I have made a function which adds rows to my html table dependent on the number of entries there are.
I am trying to make variable cdNoCell a unique ID with the id variable, which increments for each row that is made.
The problem I have is that the id prints out the total number of elements in my table in each row. So if I have 4 elements it prints out:
Actual Output:
ID Title Cost
4 a 10
4 b 12
4 c 6
4 d 10
Expected output:
ID Title Cost
1 a 10
2 b 12
3 c 6
4 d 10
My function code:
function showFunction(){
var costArrayLength = costArray.length;
for (i = 0; i<costArrayLength; i++){ //for loop adding elements to table
var table = document.getElementById("myTable");
var row = table.insertRow(-1); //adds each element to the bottom of table
var cdNoCell = row.insertCell(0);
var cdTitleCell = row.insertCell(1);
var cdCostCell = row.insertCell(2); //inserts 3 cells
var id = 1;
cdNoCell.innerHTML = id;
cdCostCell.innerHTML = costArray[i];
cdTitleCell.innerHTML = titleArray[i];
id++;
}
}
var id = 1;before your loop.