Skip to content
Advertisement

How to fire event s in a dynamically generated List in jQuery

$(document).ready(function() {


    $(".addtophundredwatchlist").click(function() {
    $.ajax({
        type : "GET",
        url : "/watchlisttophundred/",
        success : function(data){
            var raw_tag = "<ul>";
            var add_new = "Add New"
            var json_array = data.json_array;
            for (var json_count = 0; json_count < json_array.length; json_count++)
            {
                var raw_string = "<li id='watchlistitem' class='watchlistitem'>" + "<input type='button' id='watchlistbutton' class='watchlistbutton' value='*'>" + json_array[json_count].watch_list_name + "</li>"
                raw_tag = raw_tag + raw_string
            }
            raw_tag =  raw_tag + "<li id='addnew' class='addnew'>" + add_new + "</li>"
            raw_tag = raw_tag + "</ul>"
            $(".listwatchlist").html(raw_tag)
            //$(this).next().toggle();
            //alert($(".tophundredwatchlist",$(this)).html());
            //alert($(this).next().val())
            $(".tophundredwatchlist").toggle();

        }
    });
});


$(".addnew").click(function() {
    alert("Add New Clicked");
    $(".addnew").html("<input class='newwatchlisttext' name='newwatchlisttext' type='text' autocomplete='off' id='newwatchlisttext'/>")
});

$(".watchlistitem").click(function() {
    alert("Add New Clicked");
    //$(".addnew").html("<input class='newwatchlisttext' name='newwatchlisttext' type='text' autocomplete='off' id='newwatchlisttext'/>")
});

I have created a list dynamically using JavaScript and I want to invoke click event as go in normally HTML generated list. This is what I have tried so far but I could not fire a single event. Can any one help?

Advertisement

Answer

Try:


$('.addnew').delegate('li', 'click', function ()
{
    //add your code here
});
//OR
$('.addnew').live('click', function ()
{
    //add your code here
});

Advertisement