NaN
NaN

Reputation: 1306

How to delete a row with JQuery

I have a table that displays data for the user. Each row can have 2 functions, one to delete and the other to edit the record. The row itself has an id that I need to reference for both the delete and the edit functions. I am having a difficult time getting this to work correctly.

The last cell on the right is for the delete image. When I click on just the delete icon, I get an alert from the row even though I have the delete cell specified in not().

The last issue I am having is that $.post is not passing any POST value. Even if I set it manually, I cannot see it server-side.

Here is my code so far.

$('#drafts').find('tr').not(':first-child, td.delete').click( function(){
  alert(this.id);
});

$("td.delete").click(function(){
  var id = this.id;
  $.post('test.php',id, function(){
    $('#'+id).remove();
  },'json');
});

<tr id="5">
  <td>test1</td>
  <td>test2</td>
  <td class="delete">&nbsp;</td>
</tr>

Upvotes: 0

Views: 268

Answers (2)

user1823761
user1823761

Reputation:

use this code:

$("td.delete").click(function(){
  var id = $(this).parents('tr').eq(0).attr('id');
  $.post('test.php', {'id': id}, function(){
    $('#'+id).remove();
  },'json');
});

and this one for your edit action (but I don't know what do you want to do here):

$("td.edit").click(function(){
  var id = $(this).parents('tr').eq(0).attr('id');

  // now you have `id` of current row
  // write your code here
});

You said that you want the entire row for edit action, except the delete cell:

$("tr td:not(.delete)").click(function(){
  var id = $(this).parents('tr').eq(0).attr('id');
  $.post('test.php', {'id': id}, function(){
    $('#'+id).remove();
  },'json');
});

Upvotes: 2

charlietfl
charlietfl

Reputation: 171679

There is no need to use ID for the remove. Just traverse up tree to row:

$("td.delete").click(function (){
  var $row = $(this).closest('tr');
  $.post('test.php',{id: $row.attr('id')}, function(){
    $row.remove();
  },'json');
});

Upvotes: 1

Related Questions