Jquery onclick not working to add tags
I have an append <li> tag with a span class class 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 adding li to the ul tag. I am trying to remove the li tag by clicking the close icon, but the event is not working.
Could you help me.
You can assign click directly to the new 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 several, it is better to use .delegate() , as shown in @Nick's answer .
Use .delegate() here, for example:
$("#keyword").delegate(".close", "click", function (){ $(this).parent().remove(); }); .delegate() works by adding an event handler on #keyword ( <ul> ) that listens for events to bubble ... it works on the current and new .close elements under it. A less efficient .live() version looks like this:
$(".close").live("click", function (){ $(this).parent().remove(); });