4

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.

3 Answers 3

8

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

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

Comments

1

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

Comments

0
//First, obtain the td that contains 'Value2'
var $tdThatContainsValue2 = $("#someTable tr td").filter(function(){
    return $(this).html() == "Value 2";
});
//Then, obtain the first td in its row (it's first 'sibling');
$firstCellOfValue2row = $tdThatContainsValue2.siblings("td").eq(0);
alert($firstCellOfValue2row.html());  //Will show "Key 2"

Hope this helps

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.