1

I am working on an app where i need to add users dynamically from UI and delete them if required.

Adding users is working fine but deleting i am finding it difficult. I tried to recreate the scenario in jsfiddle.net https://jsfiddle.net/ce236Lf3/

code

<input type="text" class="txtadd">
<button class="btnadd">
Add
</button>

<ul class="items">

</ul>

ul{
  list-style:none;
}

.del{
  cursor:pointer;
}

$(document).ready(function(){
$('.btnadd').click(function(e){
    var txt=$('.txtadd').val();
  $('.items').append('<li class=\'listItem\'>'+txt+'<img src=\'http://icons.iconarchive.com/icons/oxygen-icons.org/oxygen/16/Actions-edit-delete-icon.png\' class=\'del\'></li>');
  $('.txtadd').val('');
});

$('.del').on('click',function(e){
    alert('hi');
  $('this').remove();
});
})
Shalini
  • 163
  • 1
  • 10
  • Read about [`Event delegation`](https://learn.jquery.com/events/event-delegation/) `$(document).on('click','.del',function(e){ alert('hi'); $('this').remove(); });` and `'this'` should be `this` while in remove handler...[Fiddle](https://jsfiddle.net/rayon_1990/ce236Lf3/1/) – Rayon Mar 03 '16 at 10:23
  • use event delegation as Rayon said and `'this'` should be `this` and as per your logic the button gets removed not the li coz click happens on button.. update the code as below `$(document).on('click','.del',function(e){ alert('hi'); $(this).parent().remove(); }); });` – RRR Mar 03 '16 at 10:30
  • @RRR, Did not notice that..Thanks for correcting.. – Rayon Mar 03 '16 at 10:34

0 Answers0