3

I am trying to dynamically add a list item to a list and then remove it by clicking on that item. The remove event never seems to fire. However if I use the same code on a static list it works fine. I've seen similar solutions but they do not work.

See jsFiddle: http://jsfiddle.net/Lc2bC/

<input id="status" type="text" placeholder="Status (tab or enter)">

<br/>
Dynamic List:
<ul id="statusList"></ul> 


$('#status').keydown(function (e) {
    if (e.which == 9 || e.which == 13) {
        $('#statusList').html($('#statusList').html() + formatNewStatus(this.value));
        this.value = "";
        this.focus();
        e.preventDefault();
    }
});

$(function () {
    $('#statusList li').click(function () {
        alert('dynamicList');
        $(this).remove();
    })
});
Papa Burgundy
  • 6,397
  • 6
  • 42
  • 48

3 Answers3

6

It's because the click() function only binds to elements that exist in the dom at the time it is called.

live() is the older technique, but is deprecated and will not be supported in future versions.

What you need to use is on()

$(function () {
    $('#statusList').on('click', 'li', function () {
        alert('dynamicList');
        $(this).remove();
    });
});
random_user_name
  • 25,694
  • 7
  • 76
  • 115
  • `live()` is not even supported in current versions -- it was removed in jQuery 1.9. Why would you even bother mentioning it, since the question never asked about it? – Barmar Jan 09 '14 at 17:02
  • 1
    All accurate information is helpful, especially for people like me who are in and out of jQuery. I didn't realize that on() replaced live(), as I don't do a lot of jquery. I actually tried to use live() at some point. Thanks for the info. – Papa Burgundy Jan 09 '14 at 17:13
2

The click function only binds to elements that were present when it was called. Use on() instead.

on()

Attach an event handler function for one or more events to the selected elements.

http://api.jquery.com/on/

Eric J.
  • 147,927
  • 63
  • 340
  • 553
2

Use on http://api.jquery.com/on/

$(function () {
    $('#statusList').on("click", "li", function () {
        alert('dynamicList');
        $(this).remove();
    })
});

FIDDLE

Merlin
  • 4,907
  • 2
  • 33
  • 51