Paul
Paul

Reputation: 11746

How do I apply a jquery Click event to dynamic list elements?

My current setup loads a dynamic list at which point I create a click event via jquery like so:

$('#listReports li').click(function () {
    var selected = $(this).text();
    alert("List Item: " + selected);
});

I have code that lets a user save a report which gets appended to the list. The new item in the list doesn't trigger the click event until I call the function again. The problem with this is for the older items the event is getting triggered twice.

Here is how I append my list items and call then function again:

            $("#save").click(function (e) {

                if ($("#reportParams li").size()> 0) {
                    var fileName = $('#reportFileName').val();

                    if (!fileName) {
                        alert("You must enter a file name!");
                    }
                    else {
                        $('#listReports').append('<li><a href="#">'+fileName+'</a></li>');

                        $('#listReports li').click(function () {
                            var selected = $(this).text();
                            alert("List Item: " + selected);
                        });
                    }
                }
            });

Is there a way to define the click event only once and have it effect new items appended to the list?

Upvotes: 3

Views: 9617

Answers (1)

Matt Ball
Matt Ball

Reputation: 359836

Instead of .click(), use .live():

$('#listReports li').live('click', function ()
{
    var selected = $(this).text();
    alert("List Item: " + selected);
});

or .delegate():

$('#listReports').delegate('li', 'click', function ()
{
    var selected = $(this).text();
    alert("List Item: " + selected);
});

Upvotes: 4

Related Questions