Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery - remove li containing link

Tags:

jquery

ajax

I have a link inside a <li> element and want the <li> element to be removed when the link is clicked. Here is my code:

<li id='i80'>
 <div class='singleitem'>
  <img src='/css/images/image.png' width='30' height='30' />
  <div id='listtext'><h1>Title</h1></div>
  <a class='delete' id='80' href='#'></a>
  <div id='helper'></div>
 </div>
</li>

And my Jquery code:

$(".delete").click(function(e){
 var del_id = $(this).attr('id');
 e.preventDefault();
 $.post("/add/delete.php", { iid: del_id } ,function(data){
  if(data.status == 'deleted');
   {
     $(this).closest("li").remove();
   }
 });
});

The ajax is working fine and the 'deleted' status is being sent back correctly, however, that one line that involves removing the parent li just doesn't work. Any ideas? Thanks.

EDIT:

I've noticed that new list items I've added dynamically to my existing ul don't work here. Is that because this just loads when the page loads initially and then won't work with with dynamically updated content?

like image 911
nbu Avatar asked Jun 04 '26 01:06

nbu


1 Answers

$(".delete").click(function(e){
 var del_btn = $(this);              // cahed
 var del_id = del_btn.attr('id');
 e.preventDefault();
 $.post("/add/delete.php", { iid: del_id } ,function(data){
  if(data.status == 'deleted');
   {
     del_btn.closest("li").remove(); // used
   }
 });
});


EDIT to fit an additional issue asked by the OP.
Use the .on() method like:
$(".singleitem").on('click', 'a.delete', function(e){
 var del_btn = $(this);              // cahed
 var del_id = del_btn.attr('id');
 e.preventDefault();
 $.post("/add/delete.php", { iid: del_id } ,function(data){
  if(data.status == 'deleted');
   {
     del_btn.closest("li").remove(); // used
   }
 });
});
like image 95
Roko C. Buljan Avatar answered Jun 05 '26 14:06

Roko C. Buljan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!