tags:

views:

53

answers:

3

Why does my jquery function runs twice on click ?

$("a").click(processAction);

function processAction(e){
    var clicked = e.target;

//show apply button.

        $("#apply").live("click",function(e){
            e.stopPropagation();
            someFunction(clicked);
            alert("this the array " + mydata);
                clicked = "";
            }); 
}   

someFunction is running twice !

+6  A: 

For every click on an a-element, you add a click handler to your #apply-element. If you click 3 times on an a-element, then click on #apply, three different instances of 'someFunction' will run.

Thomas
see jQuery's .live() method and understand javascript event handlers are chained so multiple handlers are created. http://api.jquery.com/live/
burkestar
should I add .die() method inside the #apply handler ?
Kim Jong Woo
That wouldn't solve your problem. It's hard to tell what you're trying to do. A possible fix would be to move the .live() call outside of the click handler for the a-element altogether. That would bind the handler to the #apply element right away, but only once. A click on an a-element would then simply show the previously hidden #apply element.
Thomas
Another fix would be to replace $("a").click(processHandler) with $("a").once(processHandler), but again, it's not at all clear what you're trying to do, so that may or may not be a working fix for you.
Thomas
A: 

If you are using .live() to attach the click event to that specific anchor, you don't have to attached another click event to the anchor using

$("a").click(processAction);

I'm not sure if it's intentional that you are putting the .live in the anchor click function, if it is not, you can pull out the .live() and seperate from the actual click function.

Brandon
A: 

.unbind("click").bind("click, somefunction) works beautifully.

Kim Jong Woo