1

I am dynamically adding a custom component with buttons this way

function showPopup(){
var comp = '<div id="alert"><input type="button" id="proceed"><input type="button" id="close"></div>';

$('#body').append(comp);

}

To these buttons I have handlers like this

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

$('#proceed').live('click',function(){
//ajax-call
});

Now the issue is when I call the function say n times and close it and when i do a proceed now it does n ajax calls. Any solution to this ? Thank you

Dhiraj
  • 33,140
  • 10
  • 61
  • 78
  • Are you executing the handler code snippets each time showPopup() is called? – Yardboy Jun 23 '11 at 19:52
  • I'm guessing it's not actually that way in your real code because it wouldn't work, but you are missing `()` on your `parent` call. – James Montagne Jun 23 '11 at 19:53
  • @Yardboy: no the handlers are not executed on showPopup – Dhiraj Jun 23 '11 at 20:18
  • this: "Now the issue is when I call the function say n times and close it and when i do a proceed now it does n ajax calls" confuses me - call the function n times - which function? "and close it" close what, what is "it" I think we need to see the "ajax-call" exactly. And which jQuery version are you using? – Mark Schultheiss Jun 23 '11 at 20:55

2 Answers2

2

You are adding multiple elements with the same id which is invalid markup. This will be causing problems for jQuery when it comes to delegating the event to the correct element. jQuery matches exactly one element when querying for an ID - see Does duplicate id's screw up jquery selectors?

Also, this demo seems to be working for me in Chrome 14.

Community
  • 1
  • 1
andyb
  • 43,435
  • 12
  • 121
  • 150
0

It's hard to tell for sure because you don't have the live calls in context but I assume that the calls to live are within some code that is called multiple times. If so, this is the problem. live should only be called once for each element. live will then automatically apply to all items created matching the selector. If it is called multiple times you will attach another handler each time.

James Montagne
  • 77,516
  • 14
  • 110
  • 130