0

Possible Duplicate:
Jquery adding event listeners to dynamically added elements

jQuery bit:

I append an input field with some text to a div:

        shareVisual = '<div class="individual-share">' + '<input type="number" value="1" /> X ' + classname.val() + '@' + classcurrency.val() + ' ' + classprice.val() + ' per share ' + '<button type="button" class="remove-share">Remove</button></div>';
        listOfSharesBox.append(shareVisual);

And then i try to catch an on-click event:

$("#list-of-shares").bind('click', '.remove-share', function() {
    $(".remove-share").closest("div").find(".individual-share").remove();
});

Why does the DIV not get removed?

Cheers.

P.S.

when i change my code to this:

$("#list-of-shares").bind('click', '.remove-share', function() {
    $(".remove-share").closest("div").remove();
});

All of the dynamically generated inputs get deleted within the div.

Community
  • 1
  • 1
chuckfinley
  • 2,577
  • 10
  • 32
  • 42

2 Answers2

2

If you use the jquery 1.7 means try like this

$(".remove-share").on('click',function() {
    $(this).closest("div").remove();
});

otherwise use

$(".remove-share").bind('click',function() {
    $(this).closest("div").remove();
});
muthu
  • 5,381
  • 2
  • 33
  • 41
  • I altered the code and now i have this: $(listOfSharesBox).bind('click', 'remove-share', function() { $(this).closest("div").find(".individual-share").remove(); }); Unfortunately, when i click on a button, it deletes all the DIVs within the parent div. All i want is to delete only a signle div that has a button associated with it. – chuckfinley Jan 23 '13 at 10:41
  • no yuo should not have like this $(listOfSharesBox) because listOfSharesBox is a variable not a dom object – muthu Jan 23 '13 at 10:44
-1

Try using the 'live' keyword which copes with dynamically generated controls:

$(".remove-share").live('click', function() {
$(this).closest("div").remove();
});
Maff
  • 1