Delete a table row with jQuery

December 8th, 2009 | posted in blog, jQuery | No Comments »

I will explain, shortly, how to delete a table row with jQuery Ajax post method. We will need some basic HTML example structure like the following:

<table>
    <tr>
<td class='one'>Text</td>
        <td class='two'>Some more text</td>
        <td class='action'><a style='cursor:pointer'>delete</a></td>
   </tr>
   <tr>
        <td class='one'>Text 2</td>
        <td class='two'>Some more text 2</td>
        <td class='action'><a style='cursor:pointer'>delete</a></td>
   </tr>
</table>

And you want to create a click event that deletes a row from a table, and in the same time sends a post or get request to a server that updates the database, deletes the row, you can do this with jQuery like this:

$(document).ready(function(){
    $('.action').click(function(){
       <span style="color: #339966;">//on click, mark the row for deleting by adding a class
       // 'deleting' to the tr element</span>
       $(this).parent().addClass('deleting');

      <span style="color: #339966;"> //make a post to the server, php script for example,
       // that deletes the row from a database</span>
       $.post('deleteRow.php',{
             rowId: 2  <span style="color: #339966;">//send the row id for example</span>
         },function(data){
             <span style="color: #339966;">//when the server is done with the deletion of the row
             // from the database, remove the element from the DOM tree</span>
             $('.deleting').remove();
         })
      })
})

And that’s it. Any comments are welcome.

Leave a Comment