Ekky
Ekky

Reputation: 790

HTML content is not getting on Jquery click function

In my code I have the following:

$(document).ready(function(){           
    $("input#Addmore").click(function(){
        $('div#add_div').append("<a class='remove' href='#'>X</a>");
    });         
});

This code on click of add more button and I want to remove parent div of above added code on click of "X" by jquery. for that purpose i am using this code

$("a.remove").click(function(){ 
    $(this).closest("div").remove();
});

But the code is not working because jQuery did not getting append anchor code. Can any one tell me the solution?

Upvotes: 2

Views: 116

Answers (3)

user1936191
user1936191

Reputation:

Try this

$('#add_div').delegate('a.remove', 'click', function() {
    $(this).closest("div").remove();
});

Upvotes: 2

Jignesh Rajput
Jignesh Rajput

Reputation: 3558

Or you can try this:

  $("input#Addmore").click(function(){
       $("div#add_div").append("<a class='remove' href='javascipt:;' onclick='remove(this);return false' href='#'>X<br/></a>");
});    

and here is remove function:

 window.remove = function(obj)
   {
        $(obj).closest('div').remove();
   }

see here : http://jsfiddle.net/Hvx2u/3/

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

You need to delegate the event to the nearest static element. Try this:

$('#add_div').on('click', 'a.remove', function() {
    $(this).closest("div").remove();
});

Or if you are using an older version of jQuery (less than 1.7) use delegate() like this:

$('#add_div').delegate('a.remove', 'click', function() {
    $(this).closest("div").remove();
});

Upvotes: 4

Related Questions