Melissa Doll Melissa Doll - 15 days ago 6
Javascript Question

Nested for loops returning wrong value

I have an Array of Dates. On Load I would like to parse these dates with Moment JS, then display these Dates in Column B of myTable.

What I have so far returns the last value of the Array 3 times, I am not sure why.

function loadFunction () {

var cellData = ["2016-08-24 12:45", "2016-08-24 16:00","2016-08-24 13:00"];

var myTable = document.getElementById("myTable");

var times = [];

for (var i =0; i <cellData.length; i++) {

var date = moment(cellData[i]).format('MM/DD/YYYY hh:mm a');
times.push(date);

for (var j=1; j < 6 ; j+=2) {

myTable.rows[j].cells[1].innerHTML = times[i];

}
}
}


<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>

<body onload="loadFunction()">

<table id="myTable">
<thead>
<tr>
<th colspan="3">Table</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
</tr>
<tr style="display:none;">
<td colspan="3"></td>
</tr>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
</tr>
<tr style="display:none;">
<td colspan="3"></td>
</tr>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
</tr>
<tr style="display:none;">
<td colspan="3"></td>
</tr>
</tbody>
</body>

Answer

Your second for iterates 3 times for every value. So at the last value of the cell it will set into the cell 1 3 and 5 the same value. Try to declare the variable outside the for and after the iteration change the value of j

function loadFunction () {

    var cellData = ["2016-08-24 12:45", "2016-08-24 16:00","2016-08-24 13:00"];

    var myTable = document.getElementById("myTable");

    var times = [];
    var j=1;
  
    for (var i =0; i <cellData.length; i++) {

        var date = moment(cellData[i]).format('MM/DD/YYYY hh:mm a');
        times.push(date);

        myTable.rows[j].cells[1].innerHTML = times[i];
        j += 2;
         
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>

<body onload="loadFunction()">

<table id="myTable">
    <thead>
        <tr>
            <th colspan="3">Table</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>A</td>
            <td>B</td>
            <td>C</td>
        </tr>
        <tr style="display:none;">
            <td colspan="3"></td>
        </tr>
        <tr>
            <td>A</td>
            <td>B</td>
            <td>C</td>
        </tr>
        <tr style="display:none;">
            <td colspan="3"></td>
        </tr>
        <tr>
            <td>A</td>
            <td>B</td>
            <td>C</td>
        </tr>
        <tr style="display:none;">
            <td colspan="3"></td>
        </tr>
</tbody>
</body>

Comments