views:

5616

answers:

5

Hey, I have a simple cart page that displays items that are in someones cart, and having it display via an ASP while from my table. I have a column where a user can delete an entry. I have the ASP working properly, now I am trying to add some AJAX in to it. I have the following code:

$("img.delete").click(function() {
var id     = $('#id').attr('value');  
 $.ajax({
  type: "POST",
  url: "delete.php",
  data: "id="+ id,
  success: function(){
   $('tr.selector').remove();
   $('div.success').fadeIn();
  }
 });
return false;
});

The thing is, how wouild I go about setting it up for each value, because if I use the above, I click one and they will all go. I am confused on how to set it up to work with numerous rows.

Any ideas?

Thanks,

Ryan

+3  A: 

You need to select only the item's row for removal. I'm not sure how you have it set up, but if the image element is inside the row you could use:

 $("img.delete").click(function() {
      var row = $(this).parents('tr:first');

      ...

      success: function(){
           $(row).remove(); //Remove the row containing the image element
           ...
      }

      ...
  });
Eran Galperin
That code worked great! thank you. Is the tr:first saying when you click the img, take the parent tr of the table?
Coughlin
yes, take the first tr up in the DOM chain. I use :first just in case it's nested inside another table, and also it's a stopping condition so it won't search further after finding the first tr.
Eran Galperin
A: 

Thank you Eran, now I have this:

$("img.delete").click(function(){
 var row = $(this).parents('tr:first');
 $.ajax({
  type: "POST",
  url: "delete.php",
  data: "id="+ id,
  success: function(){
   $(row).remove(); //Remove the row containing the image element
  }
 });


 return false;
});

I need to capture the ID of the row somehow, I am maybe to tr.id="ID" then retrieve it with:

 var id  = $(row).attr('id');

Would that work? I need the ID to send to my backend.

Ryan

Coughlin
If you have an id attribute for the row then that should work.
Eran Galperin
A: 

If it is the html id-attribute you want, then that would work. Why don't you try it?

EDIT: It might be just row.attr('id'); It have slipped from my mind, havn't ben using jQuery for sometime :)

finpingvin
A: 

i have done the similar thing here:

http://sarfraznawaz.wordpress.com/2009/09/14/deleting-table-rows-using-jquery-and-php/

Sarfraz
A: 

the simple thing is to attach a $variable (id) to the class of each item, say

// $("img.delete_").click(function()

in this case it appears as img.delete_1, img.delete_2 ect for each item,

then apply the same to the class of the looping item

">

hope it makes sense

$("img.delete_").click(function() { var id = $('#id').attr('value');
$.ajax({ type: "POST", url: "delete.php", data: "id="+ id, success: function(){ $('tr.selector').remove(); $('div.success').fadeIn(); } }); return false; });

ely