2

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++;
    }
}
1
  • Just put var id = 1; before your loop. Commented Mar 7, 2017 at 20:46

2 Answers 2

3

You should be able to change this line

cdNoCell.innerHTML = id;

with this

cdNoCell.innerHTML = i + 1;

Then you can remove both var id = 1; and id++; from your code.

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

Comments

2

Since you have var id = 1; inside your loop the loop will restart and output 1 each time instead of increasing as expected.

I am kind of guessing on your arrays but below you can see a working snippet. Also keep in mind the insert functions are smart enough to know the next cell or row.

titleArray = new Array("a","b", "c");
costArray = new Array(10, 20, 30);

function showFunction(){
    var costArrayLength = costArray.length;
    var id = 1;
    
    for (i = 0; i<costArrayLength; i++){ //for loop adding elements to table
        var table = document.getElementById("myTable"); 
        var row = table.insertRow(); //adds each element to the bottom of table
        var cdNoCell = row.insertCell();
        var cdTitleCell = row.insertCell();
        var cdCostCell = row.insertCell(); //inserts 3 cells 
        cdNoCell.innerHTML = id;
        cdCostCell.innerHTML = costArray[i];
        cdTitleCell.innerHTML = titleArray[i];
        id++;
    }
}

showFunction();
<table id="myTable" border=1>

</table>

Comments

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.