Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery onclick not working for append tags

Tags:

jquery

append

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.

like image 670
Elankeeran Avatar asked Jan 21 '23 01:01

Elankeeran


1 Answers

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();  
});
like image 163
Nick Craver Avatar answered Feb 01 '23 08:02

Nick Craver