jQuery delete table row on click: This article explains how to remove selected table row .i.e how to delete table row by id or class-name on button click event in jQuery. On button click, we remove the selected row/tr may be its dynamically added table row or already available on DOM.
Using jQuery `.on()` method will able to select dynamically added element by specify its class-name or Id and then using `.remove()` method its delete the selected table row. Below gif shows the demo of our working code.
Output :
Step to delete table row :
- Add html table with some data
- Use jQuery .remove() method
HTML: Add HTML table with some data ( to delete table row)
First, we have to added a table tag in our HTML page with some `tr` table row and `td` table data and a button with text as Delete. Here delete button is used to delete specific table row.Our HTML structure looks like as shown in the below written code.
//*
<table id="tbUser">
<tr>
<th>Sr</th><th>Name</th><th>Location</th><th></th>
</tr>
<tr>
<td>1</td><td>Amit</td><td>Ghatkopar</td>
<td><button class="btnDelete">Delete</button></td>
</tr>
<tr>
<td>2</td><td>Vicky</td><td>Powai</td>
<td><button class="btnDelete">Delete</button></td>
</tr>
.......... // so on data
</table>
//*
In the above table, we have added some data and in each row we have a button with a common class as “btnDelete”. Now next will add a click event on button click and on click it, will delete that row tr from out HTML table.
jQuery: Code to remove table row (tr) on button click
Here, we make a jQuery click event on button tag. Using `closest()` method we select the current row ie closest tr of our delete button, and then with `remove()` method will delete that record.Similarly for deleting the next row tr we use `.next()` method along with `.remove()` this will delete the next table row. This is how we able to delete table row our final code looks like as written below.
//*
$("#tbUser").on('click', '.btnDelete', function () {
$(this).closest('tr').remove();
});
//*
So finally we able to delete table row on button click in jQuery. If you want to read or access table cell content TD value then pls check this Complete Tutorial 4 ways get table cell td value.
Other Reference:
Post Comment
Your email address will not be published. Required fields are marked *