1

I'm trying to update table rows from an array. The assignment requirement is that the table has to be pre-existing with no data, so I'm not allowed to append row data - I need to replace the data in the cells.

HTML table

<table id="test">
  <thead>
    <tr>
      <th></th>
      <th>Jan</th>
      <th>Feb</th>
      <th>Mar</th>
    </tr>
    </thead>
    <tbody>
    <tr>
      <th>Wind Speed</th>
      <td></td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <th>Solar Radiation</th>
      <td></td>
      <td></td>
      <td></td>
    </tr>
    </tbody>
</table>

jQuery code

var arr = [[13,14,15],[3,4,5]];

$.each(arr, function(rowIndex, r){
  $.each(r, function(colIndex, c){ 
    $("td").text(c);
  });
});

It should output data from the array in the cells, but it's only outputting 5 in the empty cells, which is the last value in the last array. I'm sure I'm missing something simple, but I can't figure it out. Any help would be greatly appreciated!

1 Answer 1

3

You can do it like this:

$("#test tbody tr:eq(" + rowIndex + ") td:eq(" + colIndex + ")").text(c);

Problem is that when you use $("td").text(c); you set each td with the same value.

Working demo

var arr = [
  [13, 14, 15],
  [3, 4, 5]
];

$.each(arr, function(rowIndex, r) {
  $.each(r, function(colIndex, c) {
    $("#test tbody tr:eq(" + rowIndex + ") td:eq(" + colIndex + ")").text(c);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="test">
  <thead>
    <tr>
      <th></th>
      <th>Jan</th>
      <th>Feb</th>
      <th>Mar</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>Wind Speed</th>
      <td></td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <th>Solar Radiation</th>
      <td></td>
      <td></td>
      <td></td>
    </tr>
  </tbody>
</table>

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

1 Comment

@JasonCollier No problem happy to help

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.