Robin Andrews
Robin Andrews

Reputation: 3794

JQuery get table row and contents as HTML

I want to use JQuery to get a table row and its contents as HTML.

var updateButton = $( this );
var currentRow = updateButton.closest( 'tr' );
window.console.log( currentRow );

but the resulting log doesn't seem to contain the table values input by the user.

I've found answers about how to extract the data, but I want to be able to reproduce the row as html with the existing contents in the cells so I can output a copy of the row.

Can this be done with a simple JQuery function, or do I need to rebuild the row using some combination of the result of my above code and the extracted data?

Upvotes: 0

Views: 43

Answers (2)

Rahul Mahadik
Rahul Mahadik

Reputation: 12271

  $(".btn-copy").on('click', function(){  
    var ele = $(this).closest('tr').clone(true);
    console.log(ele)
    $(this).closest('tr').after(ele);//this will duplicate tr
  })
table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>action</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td><button class="btn-copy">Click to copy</button></td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td><button class="btn-copy">Click to copy</button></td>
  </tr>
</table>

Hope this helps you

Upvotes: 1

Tendai
Tendai

Reputation: 147

use parent if the button is inside the row.

<tr>...<td><button class="update-button">update</button></tr>

  <script>
    $(".update-button").on("click",function(){
        console.log($(this).parent("tr"));
    })
</script>

Upvotes: 0

Related Questions