11

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Steve Walsh
  • 6,363
  • 12
  • 42
  • 54

4 Answers4

21
$(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);
    });

} );
maxedison
  • 17,243
  • 14
  • 67
  • 114
4

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);
  });
});
John Hartsock
  • 85,422
  • 23
  • 131
  • 146
1

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
    });
} );
Dennis
  • 32,200
  • 11
  • 64
  • 79
1

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>');
});
Korvin Szanto
  • 4,531
  • 4
  • 19
  • 49