Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Jquery, replace one row in table with a new one

Say I have a table:

<table id="mytable">
      <tr class="old_row"><td>1</td><td>2</td><td class="edit">Edit</td></tr>
      <tr class="old_row"><td>1</td><td>2</td><td class="edit">Edit</td></tr>
      <tr class="old_row"><td>1</td><td>2</td><td class="edit">Edit</td></tr>
</table>

I want to click on the <td>Edit</td> cell and use jquery to replace the entire row with a new row with more content, e.g.

    $(document).ready(function() {

        $('#mytable .edit').click( function() {

            var tr = $(this).parent();
            var new_row = '<tr class="new_row"><td>3</td><td>4</td><td>Save</td></tr>'
            // code to replace this row with the new_row
        });

    } );

Any idea how this could be done?

like image 907
Steve Walsh Avatar asked Sep 22 '11 15:09

Steve Walsh


4 Answers

$(document).ready(function() {

    $('#mytable .edit').click( function() {

        var new_row = '<tr class="new_row"><td>3</td><td>4</td><td>Save</td></tr>'
        $(this).parent().replaceWith(new_row);
    });

} );
like image 72
maxedison Avatar answered Oct 21 '22 04:10

maxedison


Use jQuery.replaceWith()

$(document).ready(function() {
  $('#mytable .edit').click( function() {
    var tr = $(this).parent();
    var new_row = '<tr class="new_row"><td>3</td><td>4</td><td>Save</td></tr>';
    tr.replaceWith(new_row);
  });
});
like image 40
John Hartsock Avatar answered Oct 21 '22 02:10

John Hartsock


jQuery's replaceWith(). Example:

$(document).ready(function() {
    $('#mytable .edit').click( function() {

        var tr = $(this).parent();
        var new_row = '<tr class="new_row"><td>3</td><td>4</td><td>Save</td></tr>'
        tr.replaceWith(new_row); // code to replace this row with the new_row
    });
} );
like image 1
Dennis Avatar answered Oct 21 '22 04:10

Dennis


http://jsfiddle.net/hAvyv/

$('.edit').click(function(){
    $(this).parent().removeClass('old_row').addClass('new_row').html('<td>3</td><td>4</td><td>Save</td>');
});
like image 1
Korvin Szanto Avatar answered Oct 21 '22 03:10

Korvin Szanto