Get the contents of a table row with a button click

JavascriptJqueryButtonOnclickHtml Table

Javascript Problem Overview


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>

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

Solution 3 - Javascript

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

Solution 4 - Javascript

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()"

Solution 5 - Javascript

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
    });
});

Solution 6 - Javascript

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 );
    });
});

Solution 7 - Javascript

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

Solution 8 - Javascript

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>[email protected]</td>
		<td>click</td>
      </tr>
      <tr>
        <td>Mary</td>
        <td>Moe</td>
        <td>[email protected]</td>
		<td>click</td>
      </tr>
      <tr>
        <td>July</td>
        <td>Dooley</td>
        <td>[email protected]</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>

Solution 9 - Javascript

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>

Solution 10 - Javascript

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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionchuckfinleyView Question on Stackoverflow
Solution 1 - JavascriptmartynasView Answer on Stackoverflow
Solution 2 - JavascriptRory McCrossanView Answer on Stackoverflow
Solution 3 - JavascriptManseView Answer on Stackoverflow
Solution 4 - Javascriptcody collicottView Answer on Stackoverflow
Solution 5 - JavascriptdgvidView Answer on Stackoverflow
Solution 6 - JavascriptdevView Answer on Stackoverflow
Solution 7 - JavascriptMuhammad Waqas AzizView Answer on Stackoverflow
Solution 8 - JavascriptankushView Answer on Stackoverflow
Solution 9 - JavascriptMuhammad ZakariaView Answer on Stackoverflow
Solution 10 - JavascriptBoMBxDEVView Answer on Stackoverflow