Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change value of a particular TD in a row with JQuery or Javascript?

So if I have table:

<table id="someTable">
  <tr><td>Key1</td><td>Value1</td></tr>
  <tr><td>Key2</td><td>Value2</td></tr>
  <tr><td>Key3</td><td>Value3</td></tr>
</table>

Is there a way I can get the "index of the row" of value 2 and store the value "Key2" into a variable. Then using that "index of the row containing value2", I change the "first TD"(or if there were three TD's, get the 3rd TD) of that row to something like "changed key"?

Something like "index of tr" and then specifying "index of td" to change... not sure if that is possible with jquery or javascript.

like image 904
Tesselate Avatar asked Jan 19 '23 21:01

Tesselate


2 Answers

If you know the index of the row and cell, you could do something like this:

$(document).ready(function(){
    $('#someTable tr:nth-child(2) td:nth-child(1)').html('foo');
});

You can also pull the current value of the cell using the same selector, but .html() rather than .html(content)

Fiddle here

like image 93
Demian Brecht Avatar answered Feb 13 '23 17:02

Demian Brecht


If you pass jQuery a td, you can get the index of it's containing row (relative to the other rows) with $(obj).parents("tr").index(); //obj is the td object passed in You can do the same to the table cell: $("#yourtable td").eq(index).text("Your Value"); //index is the index you wanna grab

like image 26
Thomas Shields Avatar answered Feb 13 '23 17:02

Thomas Shields