user1607759
user1607759

Reputation:

Update Table Cell Data w/jQuery

This is my table format.

<table id="table1">
 <tr id="row_1">
  <th>Some Heading</th>
  <td class="t1"></td>
  <td class="t2"></td>
  <td class="t3"></td>
  <td class="t4"></td>
 </tr>
 <tr id="row_2">
  <th>Some Heading</th>
  <td class="t1"></td>
  <td class="t2"></td>
  <td class="t3"></td>
  <td class="t4"></td>
 </tr>
 etc...
</table>

How do I update the content of the separate table cells (td) using jQuery? A better way to put it would be how do I write it if I want to update the content of #row_1 cell 1 or #row_2 cel 4, etc?

I have another table which I can update data in no problem, but it's also a lot simpler. It only has one table cell per row that needs content updated. I did it using this.

$('#val_' + i).html("stuff I put in it");

Each cell has a unique id - #val_ + some number identifying it so I can easily loop through it, but the slightly more complex table is giving me trouble.

Upvotes: 1

Views: 4075

Answers (2)

nbrooks
nbrooks

Reputation: 18233

$('#table1').children('tr').each(function() {

    // where 'x' is the index of the <td> to target
    var $requiredCell = $(this).children('td').eq(x);

    doStuff( $requiredCell );

});

Or if you're just targeting a single cell overall

$('#row_1 td.t1');

Or

$('#row_1 td').first(); // If you can't use the classes...

Or

$('#row_1 td').eq(x); // for targeting a td at an arbitrary index 'x'

e.g. (from your question):

$('#row_1 td').eq(3); // target the fourth <td>. Note index is 0-based

Upvotes: 1

Kaeros
Kaeros

Reputation: 1138

To get all the tds you can use something like this.

$("#row_1").find('td').each {function() {
  // do something
});

To get a specific td you can do this:

$('#row_1 .t1').something();

Upvotes: 0

Related Questions