Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove table row using jQuery

Tags:

jquery

The following is my code

Script

$(document).ready(function(){
    $('#click').click(function(){
        $('#table').append('<tr><td>&nbsp;</td></tr>');
    })
    $('#remove').click(function(){
        $('#table').remove('<tr><td>&nbsp;</td></tr>');
    })
})

HTML

<table width="100%" border="1" cellspacing="0" cellpadding="0" id="table">
    <tr>
        <td>&nbsp;</td>
    </tr>
    <tr>
        <td>&nbsp;</td>
    </tr>
</table>
<div id="click">click</div>
<div id="remove">remove</div>

When I add a row it works great, but I don't know how to delete the last row of the table. You can also check the online demo.

How can I do this?

In addition, I want when the user also clicks on any row it will delete itself. I have tried out, but there is a problem. If you click on the row it is deleting itself, but when you add a row by clicking in #click then the row is not deleting itself by clicking on it.

Here is my code:

Script

$(document).ready(function(){
    $('#click').click(function(){
        $('#table').append('<tr><td>&nbsp;</td></tr>');
    })
    $('#remove').click(function(){
        $('#table tr:last').remove();
    })
    $('#table tr').click(function(){
        $(this).remove();
    });
})
like image 416
Kamal Avatar asked May 19 '12 05:05

Kamal


2 Answers

If you want to remove the last table row of #table, you need to target it with your selector, and then call $.remove() against it:

$('#remove').on("click", function(){
    $('#table tr:last').remove();
})
like image 75
Sampson Avatar answered Nov 02 '22 20:11

Sampson


You can't remove like that you have to specify which node you want to remove $('#table tr:first') and the remove it remove()

$('#remove').click(function(){
    $('#table tr:first').remove();
})

http://jsfiddle.net/2mZnR/1/

like image 45
yokoloko Avatar answered Nov 02 '22 20:11

yokoloko