Kamal
Kamal

Reputation: 2180

Delete row using jQuery

I want the following functionality:

When the user clicks on any row it will get deleted.

I have tried the following, but there is a problem. If you click on the row it gets deleted fine, but when you add row by clicking on #click, the row is not getting deleted when I click on it.

Here's 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();

});
})

Upvotes: 1

Views: 135

Answers (3)

Dhiraj
Dhiraj

Reputation: 33618

You shoud bind a click handler to each row using on (tr)

.on() method attaches event handlers to the currently selected set of elements

$('your-table').on('click','tr',function(){
   $(this).remove();        
});

DEMO

Hope this helps

Upvotes: 1

Taha Paksu
Taha Paksu

Reputation: 15616

Because you are not assigning the event to the appended row. Try appending the row like this:

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

Upvotes: 0

icktoofay
icktoofay

Reputation: 129001

click just forwards to bind, and bind only binds to what matches the elements in the jQuery object at the time of creation. You probably want to use on with its selector parameter:

$('#table').on('click', 'tr', function() {
    $(this).remove();
});

Try it on JSFiddle.

Upvotes: 4

Related Questions