Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery basic: How can i remove a table row when a button of this row is clicked?

Tags:

jquery

$("#tableid tbody:last").append(html);

This creates table rows dynamically. Each newly created row has a "remove" button.

Now if i click that remove button that row will be deleted. How can i do this.

Thanks in advance.

like image 798
prime Avatar asked Jul 26 '11 14:07

prime


People also ask

How do you delete a row in a table using jQuery?

The jQuery remove() method is used to remove a row from HTML table. jQuery remove() Method: This method removes the selected elements alongwith text and child nodes. This method also removes data and events of the selected elements. Parameters: It accepts single parameter selector which is optional.

How do you delete a specific row from a table in JavaScript?

The deleteRow() method removes the row at the specified index from a table. Tip: Use the insertRow() to create and insert a new row.


2 Answers

 $(buttonSelector).live ('click', function ()
 {
    $(this).closest ('tr').remove ();
 }
 );

using .live to bind your event will bind it automatically when your row is dynamically added.

Edit

live is now deprecated, since version 1.7 I think.

The way to go now is using on instead of live.

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

See the doc.

like image 100
Johnny5 Avatar answered Sep 21 '22 21:09

Johnny5


You can use this code to delete the parent row containing the clicked button:

$(myButtonSelector).click(function(){
    $(this).parents('tr').first().remove();
});

For a live example see this link.

For more information see this article.

like image 32
Justin Ethier Avatar answered Sep 20 '22 21:09

Justin Ethier