0

I'm trying to add an event listener to items that don't exit yet. I will be adding the items dynamically, but I would like them to have event listener when they are added to the DOM. I have used the .on() function but this only works for items that are on the page when it loads and not for items added dynamically. The following is my code:

$(document).ready(function () {
    var $add_button = $('#add-item')
    var newItem;
    var $incompleteTasks = $('#incomplete-tasks');

    $('button.check').on("click", function () {

        alert('Helloww');
    });

    $add_button.click(function () {

        newItem = $('#new-task').val();

        //create li element and assign it to variable
        var li = $('<li></li>');
        var label = $('<label></label>');
        var button = $('<button class="check">Check</button>');

        //Use input value as the text for li item
        label.text(newItem);


        //append new item to incomplete tasks ul

        $incompleteTasks.append(li);
        li.append(label);
        li.append(button);

    });

});

I'm not sure where I'm going wrong here.

Thank you for the help.

mplungjan
  • 134,906
  • 25
  • 152
  • 209
Abdi
  • 369
  • 3
  • 12
  • 2
    You are looking for event delegation: https://learn.jquery.com/events/event-delegation/ – BeNdErR Mar 22 '15 at 22:15
  • `on` is the correct method for event handling on future elements, but you need to use the correct overload. You should use the three-parameter version, and use a parent element as the selector: `$(parent).on('click', 'futureElementSelector', callback);` – Cᴏʀʏ Mar 22 '15 at 22:19
  • @mplungjan I got the answer from the thread you provided. For some reason I was sure this was asked before, just couldnt find that thread. Appreciate the help. – Abdi Mar 22 '15 at 22:33

1 Answers1

1

you can use delegate() or on() for this purpose

see delegate and on

Note: As of jQuery 1.7, .delegate() has been superseded by the .on() method

In your case you are not giving selection with respect to parent

$("parent_selection").on('click', 'actual_element' ,function(){});

for example use this

$('#incomplete-tasks').on("click",'.check',function(){

alert('Helloww'); 
});
A.B
  • 17,478
  • 3
  • 28
  • 54