user269431
user269431

Reputation: 155

dynamically add remove rows in table using jquery

I have construted my table as follows:

    <table id="dataTable">
            <thead>
                <tr><th>Name</th>
               <th>Value</th></tr>
            </thead>
<TR><TD>Scooby Doo</TD><TD>6</TD><TD><INPUT TYPE="Button"  onClick="AddRow()" VALUE="Add Row"></TD></TR>
</table>

When the button Add Row is clicked, I need to change the button to a delete button and insert a new row on the first line. The first line must contain the same as in the code. How can I do this?

On clicking the delete button, Imust be able to delete the row to which the delete button belong?

Upvotes: 2

Views: 11321

Answers (2)

rahul
rahul

Reputation: 187030

Hope this helps

$(function(){
  $("input[type='button'].AddRow").toggle(
     function(){
       var el = $(this);
       el.closest('tr').clone(true).prependTo(el.closest('table'));
       el.attr("value", "Delete row");
     },
     function(){ 
       $(this).closest('tr').remove();          
  });
});

<table id="dataTable" border="1">
    <thead>
        <tr>
            <th>
                Name
            </th>
            <th>
                Value
            </th>
        </tr>
    </thead>
    <tr>
        <td>
            Scooby Doo
        </td>
        <td>
            6
        </td>
        <td>
            <input type="Button" value="Add Row" class="AddRow">
        </td>
    </tr>
 </table>

Working Demo

Upvotes: 8

Tim
Tim

Reputation: 9489

Something like?

$('#dataTable thead').prepend('<tr><th>Name</th><th>Value</th></tr>');

And for the deleting:

$('#dataTable thead tr').click(function() {
$(this).hide(); //hide the row, this doesn't delete it.
});

.

Upvotes: 1

Related Questions