Elankeeran
Elankeeran

Reputation: 6184

jquery onclick not working for append tags

I have append <li> tag with close class span tag

HTML code

<ul id="keyword">

</ul>

jquery

$("#btnadd").click(function() {
                addkey = document.getElementById("txtaddkey").value;
                if(addkey!=""){
                $('#keyword').append('<li><span>'+addkey+'</span><span class=\"amountin\"><a href=\"#\">$0.05</a> $ <input type=\"text\" maxlength=\"5\"/></span><span class=\'close ui-icon \'></span></li>');
                $('#txtaddkey').val('');
                }
            });
    $(".close").click(function (){
                $(this).parent().remove();  
            });

after li append in the ul tag I am try remove the li tag by click close icon but event not working.

Could you please any help me.

Upvotes: 4

Views: 6289

Answers (2)

user113716
user113716

Reputation: 322462

You could assign the click directly to the newly create element:

$("#btnadd").click(function() {
             // Made it a local variable by using "var"
            var addkey = document.getElementById("txtaddkey").value;
            if(addkey!=""){
                $('<li><span>'+addkey+'</span><span class=\"amountin\"><a href=\"#\">$0.05</a> $ <input type=\"text\" maxlength=\"5\"/></span><span class=\'close ui-icon \'></span></li>')
                    .find('.close').click(function (){
                        $(this).parent().remove();  
                    })
                    .end().appendTo('#keyword');
                $('#txtaddkey').val('');
            }
        });

or if there are going to be several of these, better to use .delegate() as seen in @Nick's answer.

Upvotes: 2

Nick Craver
Nick Craver

Reputation: 630369

Use .delegate() here, like this:

$("#keyword").delegate(".close", "click", function (){
  $(this).parent().remove();  
});

.delegate() works by adding an event handler on #keyword (the <ul>) which listens for events to bubble up...it works on current and newly added .close elements beneath it. The less efficient .live() version looks like this:

$(".close").live("click", function (){
  $(this).parent().remove();  
});

Upvotes: 7

Related Questions