2

I am creating a dynamic list of tasks that appear after the input is written and input's length is less or equal 30 characters and the button is pressed.

Together with the task there is a trash icon created.

I want to enable the user to remove chosen task when he clicks on the icon which comes from the external library ionicons.

I have an issue that when the trash icon is clicked, it removes this Li and all Li elements that were created after that clicked Li.

I am prepending li elements to the list.

Here's the snippet:

$('#addNewTaskBtn').click(function () {
    var inputText = $('#dayTask').val();
    var trashIcon = '<i class="ion-trash-b"></i>';
    var newTask = $('<li />', { html: inputText + " " + trashIcon });

    //  clearing the input after click
    $('#dayTask').val('');

    if (inputText.length && inputText.length <= 30)
        $(newTask).prependTo('ul.dayList');

    $('.ion-trash-b').click(function () {
        $(newTask).remove();
    });
});

My question is: How to remove only the one Li element which trash icon is clicked, and not all Li element (including the one) that were created later?

Thank you very much for your help.

Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55
mjrdnk
  • 233
  • 3
  • 9
  • 2
    Welcome so SO. Very well written question with appropriate amount of code and effort. Addition of the UL html would have been the icing on the cake :) – mplungjan Feb 13 '16 at 17:34

2 Answers2

1
$('.ion-trash-b').click(function(){
  $(this).parent().remove(); // or $(this).closest("li").remove();
});

or even assign it onload to attach to all future trash icons using event delegation

$(function() {
  $("#listContainer").on("click",".ion-trash-b",function(){
    $(this).parent().remove();// or $(this).closest("li").remove();
  });
});

where listContainer is the ID of the UL

Community
  • 1
  • 1
mplungjan
  • 169,008
  • 28
  • 173
  • 236
1

Remove the closest li of the clicked ion-trash-b and as your elements are dynamically generated, use event delegation for ion-trash-b click event like following.

$('#addNewTaskBtn').click(function () {
    var inputText = $('#dayTask').val();
    var trashIcon = '<i class="ion-trash-b"></i>';
    var newTask = $('<li />', { html: inputText + " " + trashIcon });

    //  clearing the input after click
    $('#dayTask').val('');

    if (inputText.length && inputText.length <= 30)
        $(newTask).prependTo('ul.dayList');        
});

$('body').on('click', '.ion-trash-b', function () {
    $(this).closest('li').remove();
});
Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55