97

I need to extract the details of each column in my table. For example, column "Name/Nr.".

  • The table contains a number of addresses
  • The very last column of each row has a button that lets a user choose a listed address.

Problem: My code only picks up the first <td> that has a class nr. How do I get this to work?

Here's the jQuery bit:

$(".use-address").click(function() {
    var id = $("#choose-address-table").find(".nr:first").text();
    $("#resultas").append(id); // Testing: append the contents of the td to a div
});

Table:

<table id="choose-address-table" class="ui-widget ui-widget-content">
    <thead>
        <tr class="ui-widget-header ">
            <th>Name/Nr.</th>
            <th>Street</th>
            <th>Town</th>
            <th>Postcode</th>
            <th>Country</th>
            <th>Options</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td class="nr"><span>50</span>
            </td>
            <td>Some Street 1</td>
            <td>Leeds</td>
            <td>L0 0XX</td>
            <td>United Kingdom</td>
            <td>
                <button type="button" class="use-address" />
            </td>
        </tr>
        <tr>
            <td class="nr">49</td>
            <td>Some Street 2</td>
            <td>Lancaster</td>
            <td>L0 0XX</td>
            <td>United Kingdom</td>
            <td>
                <button type="button" class="use-address" />
            </td>
        </tr>
    </tbody>
</table>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
chuckfinley
  • 2,577
  • 10
  • 32
  • 42

10 Answers10

299

The object of the exercise is to find the row that contains the information. When we get there, we can easily extract the required information.

Answer

$(".use-address").click(function() {
    var $item = $(this).closest("tr")   // Finds the closest row <tr> 
                       .find(".nr")     // Gets a descendent with class="nr"
                       .text();         // Retrieves the text within <td>

    $("#resultas").append($item);       // Outputs the answer
});

VIEW DEMO

Now let's focus on some frequently asked questions in such situations.

How to find the closest row?

Using .closest():

var $row = $(this).closest("tr");

Using .parent():

You can also move up the DOM tree using .parent() method. This is just an alternative that is sometimes used together with .prev() and .next().

var $row = $(this).parent()             // Moves up from <button> to <td>
                  .parent();            // Moves up from <td> to <tr>

Getting all table cell <td> values

So we have our $row and we would like to output table cell text:

var $row = $(this).closest("tr"),       // Finds the closest row <tr> 
    $tds = $row.find("td");             // Finds all children <td> elements

$.each($tds, function() {               // Visits every single <td> element
    console.log($(this).text());        // Prints out the text within the <td>
});

VIEW DEMO

Getting a specific <td> value

Similar to the previous one, however we can specify the index of the child <td> element.

var $row = $(this).closest("tr"),        // Finds the closest row <tr> 
    $tds = $row.find("td:nth-child(2)"); // Finds the 2nd <td> element

$.each($tds, function() {                // Visits every single <td> element
    console.log($(this).text());         // Prints out the text within the <td>
});

VIEW DEMO

Useful methods

  • .closest() - get the first element that matches the selector
  • .parent() - get the parent of each element in the current set of matched elements
  • .parents() - get the ancestors of each element in the current set of matched elements
  • .children() - get the children of each element in the set of matched elements
  • .siblings() - get the siblings of each element in the set of matched elements
  • .find() - get the descendants of each element in the current set of matched elements
  • .next() - get the immediately following sibling of each element in the set of matched elements
  • .prev() - get the immediately preceding sibling of each element in the set of matched elements
martynas
  • 12,120
  • 3
  • 55
  • 60
  • What if I have a popup and I want to access a table from the page and delete the row? I tried one of the method, but it's not working for me :/ – Si8 Jul 19 '14 at 14:41
  • Can you prepare a jsFiddle? – martynas Jul 19 '14 at 14:43
  • 1
    Here I have similar issue whle handling dynamic ID values. Please have a look http://stackoverflow.com/questions/25772554/jquery-how-to-read-dynamically-generated-html-table-rows-td-value – Sanjeev4evr Sep 10 '14 at 18:37
  • Please help me with this question I have here: http://stackoverflow.com/questions/26004056/how-to-retrieve-the-tr-data-on-the-same-row-within-gridview-using-jquery-modal-w (Thanks) – SearchForKnowledge Sep 23 '14 at 20:52
  • Mine is showing blank and not getting the text for some reason :/ – SearchForKnowledge Sep 23 '14 at 21:00
  • 5
    Dunno how this answer is not much more upvoted. Excelent tips! Just wanted to add you can always get the column value like this after getting the specific row $(this).closest("tr").find("td:eq(2)").html(); You will be getting the number 2 column. Cheers! – Matias Jul 14 '15 at 12:56
  • This is not working for me I have the same problem, need to read row data on click – Hitesh Kumar Mar 16 '20 at 11:09
  • Thanks a lot, how can we achieve the exact same thing using pure javascript ? – Praveen Kishor Mar 25 '20 at 18:06
  • Thanks a lot. This works fine but how about if i want to use that id on another page? – Masaba James Moses Apr 21 '20 at 21:47
13

You need to change your code to find the row relative to the button which was clicked. Try this:

$(".use-address").click(function() {
    var id = $(this).closest("tr").find(".nr").text();
    $("#resultas").append(id);
});

Example fiddle

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
12

Try this:

$(".use-address").click(function() {
   $(this).closest('tr').find('td').each(function() {
        var textval = $(this).text(); // this will be the text of each <td>
   });
});

This will find the closest tr (going up through the DOM) of the currently clicked button and then loop each td - you might want to create a string / array with the values.

Example here

Getting the full address using an array example here

Manse
  • 37,765
  • 10
  • 83
  • 108
4
function useAdress () { 
var id = $("#choose-address-table").find(".nr:first").text();
alert (id);
$("#resultas").append(id); // Testing: append the contents of the td to a div
};

then on your button:

onclick="useAdress()"
Ahmed Sunny
  • 2,160
  • 1
  • 21
  • 27
cody collicott
  • 261
  • 2
  • 6
  • 1
    That has the same problem as the code in the question--it always gets the id from the first row in the table, regardless of which row's button was the one clicked. – dgvid Jan 22 '13 at 14:21
3

The selector ".nr:first" is specifically looking for the first, and only the first, element having class "nr" within the selected table element. If you instead call .find(".nr") you will get all of the elements within the table having class "nr". Once you have all of those elements, you could use the .each method to iterate over them. For example:

$(".use-address").click(function() {
    $("#choose-address-table").find(".nr").each(function(i, nrElt) {
        var id = nrElt.text();
        $("#resultas").append("<p>" + id + "</p>"); // Testing: append the contents of the td to a div
    });
});

However, that would get you all of the td.nr elements in the table, not just the one in the row that was clicked. To further limit your selection to the row containing the clicked button, use the .closest method, like so:

$(".use-address").click(function() {
    $(this).closest("tr").find(".nr").each(function(i, nrElt) {
        var id = nrElt.text();
        $("#resultas").append("<p>" + id + "</p>"); // Testing: append the contents of the td to a div
    });
});
dgvid
  • 26,293
  • 5
  • 40
  • 57
0

Find element with id in row using jquery

$(document).ready(function () {
$("button").click(function() {
    //find content of different elements inside a row.
    var nameTxt = $(this).closest('tr').find('.name').text();
    var emailTxt = $(this).closest('tr').find('.email').text();
    //assign above variables text1,text2 values to other elements.
    $("#name").val( nameTxt );
    $("#email").val( emailTxt );
    });
});
Billu
  • 2,733
  • 26
  • 47
0
var values = [];
var count = 0;
$("#tblName").on("click", "tbody tr", function (event) {
   $(this).find("td").each(function () {
       values[count] = $(this).text();
       count++;
    });
});

Now values array contain all the cell values of that row can be used like values[0] first cell value of clicked row

0

Here is the complete code for simple example of delegate

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</head>
<body>

<div class="container">
  <h2>Striped Rows</h2>
  <p>The .table-striped class adds zebra-stripes to a table:</p>            
  <table class="table table-striped">
    <thead>
      <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Email</th>

      </tr>
    </thead>
    <tbody>
      <tr>
        <td>John</td>
        <td>Doe</td>
        <td>john@example.com</td>
        <td>click</td>
      </tr>
      <tr>
        <td>Mary</td>
        <td>Moe</td>
        <td>mary@example.com</td>
        <td>click</td>
      </tr>
      <tr>
        <td>July</td>
        <td>Dooley</td>
        <td>july@example.com</td>
        <td>click</td>
      </tr>

    </tbody>
  </table>
  <script>
  $(document).ready(function(){
  $("div").delegate("table tbody tr td:nth-child(4)", "click", function(){
  var $row = $(this).closest("tr"),        // Finds the closest row <tr> 
    $tds = $row.find("td:nth-child(2)");
     $.each($tds, function() {
        console.log($(this).text());
        var x = $(this).text();
        alert(x);
    });
    });
});
  </script>
</div>

</body>
</html>
ankush
  • 121
  • 1
  • 12
0

place folowing code in header section

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

define the table in body as

<table class="table table-hover">
            <tr>
                <th>Name/Nr.</th>
                <th>Street</th>
                <th>Town</th>
                <th>Postcode</th>
                <th>Country</th>
                <th>View</th>
            </tr>
            
            <tr>
                 <td class="nr"><span>50</span></td>
                 <td>Some Street 1</td>
                 <td>Leeds</td>
                 <td>L0 0XX</td>
                 <td>United Kingdom</td>
                 <td><button type="button" class="btn grabId" >View</button></td>
            </tr>
            
</table>

then use this script

<script>
    $(".grabId").click(function() {
        var $row = $(this).closest("tr");    // Find the row
        var $siteId = $row.find(".siteId").text(); // Find the text
        alert($siteId);
    });
</script>
Muhammad Zakaria
  • 1,269
  • 6
  • 14
0

Try this, just select javascript or jquery If you don't have header column, don't minus by 1

function rowClicked(element){
    var rowJavascript = element.parentNode.parentNode;
    var rowjQuery = $(element).closest("tr");
    
    var rowIndexJavascript = rowJavascript.rowIndex-1;
    var rowIndexjQuery = rowjQuery[0].rowIndex-1;
    
    console.log("rowIndexJavascript : ",rowIndexJavascript);
    console.log("rowIndexjQuery : ",rowIndexjQuery);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<th>Row ID</th>
<th>Button</th>
</tr>
<tr>
<td>0</td><td><button type="button"  onclick="rowClicked(this)">test1</button></td>
</tr>
<tr>
<td>1</td><td><button type="button" onclick="rowClicked(this)">test2</button></td>
</tr>
<tr>
<td>2</td><td><button type="button" onclick="rowClicked(this)">test3</button></td>
</tr>
</table>
BoMBxDEV
  • 21
  • 2