Kemat Rochi
Kemat Rochi

Reputation: 952

How to delete a row in a table using jQuery?

I have a Bootstrap table as follows,

<table class="table table-striped table-bordered">
    <tr><th>First Name</th><th>Last Name</th><th>Age</th><th>Delete</th></tr>
    <tr><td>Mickey</td><td>Mouse</td><td>5</td><td><button type="submit" class="btn btn-default btn-sm"><span class="glyphicon glyphicon-trash"></span></button></td>
    <tr><td>Tom</td><td>Cat</td><td>6</td><td><button type="submit" class="btn btn-default btn-sm"><span class="glyphicon glyphicon-trash"></span></button></td>
    <tr><td>Pooh</td><td>Bear</td><td>4</td><td><button type="submit" class="btn btn-default btn-sm"><span class="glyphicon glyphicon-trash"></span></button></td>
    <tr><td>Donaled</td><td>Duck</td><td>7</td><td><button type="submit" class="btn btn-default btn-sm"><span class="glyphicon glyphicon-trash"></span></button></td>
    <tr><td>Jerry</td><td>Mouse</td><td>8</td><td><button type="submit" class="btn btn-default btn-sm"><span class="glyphicon glyphicon-trash"></span></button></td>
</table

Whenever a user clicks on the trash button, that specific row should get deleted. How can I accomplish that using jQuery?

Here's a link to what I've got so far - http://jsbin.com/gabodamace/edit?html,output

Thanks in advance!

Upvotes: 2

Views: 7703

Answers (2)

Jagrati
Jagrati

Reputation: 12222

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

In your code add class="btn btn-default btn-sm delete. Adding a class delete will help you to use btn classes in other handlers also. .remove() function removes the whole html for that selector.

Refer to jsFiddle: https://jsfiddle.net/jagrati16/o7bu09jr/1/

Upvotes: 2

Vishnu Sharma
Vishnu Sharma

Reputation: 642

Do like below:

$('.btn-default').click(function(){
  $(this).parents('tr').remove();
})

Try Demo: JsFiddle

Upvotes: 3

Related Questions