Stop onClick from firing twice using jQuery

I am using jQuery.post to perform an action when the user clicks on an external link. I have attached the onClick event to the link:

<a id="lib-geo57" onClick="javascript:dConvert('lib-geo','57');"

      

The event fires, but this action should only be performed once. To avoid the second firing, I thought about removing the onClick attribute:

function dConvert(a,k){
    $.post("dConverter",{aid:a,key:k});
    $("#"+a+k).removeAttr('onclick');
};

      

but that won't work. I have also tried

$("#"+a+k).attr('onclick','');

      

without success. The mail function continues to work in both of the above examples.

Why can't I remove or change the onClick attribute? What would be the best strategy to prevent my post from being executed more than once?

+2


source to share


4 answers


using one()

will remove the event handler after the first click of the link <a>

.

$('#lib-geo57').one('click', function() {
    $.post("dConverter",{aid:'lib-geo',key:'57'});
});

      

or you can define a click event with jQuery and then remove with jQuery too (but that's essentially what the use one()

is anyway).

$('#lib-geo57').bind('click', function() {
    $.post("dConverter",{aid:'lib-geo',key:'57'});
    $(this).unbind('click');
});

      



If you stick with the inline attribute onclick

, you just need to assign null to the property to remove the event handler after the first click.

function dConvert(a,k){
    $.post("dConverter",{aid:a,key:k});
    $("#"+a+k)[0].onclick = null;
};

      

As another poster pointed out , this change is client side and therefore will not persist in the update page. You will need to come up with some kind of mechanism to save the changes if that's what you need. Most web frameworks have a mechanism for this.

+14


source


You can cancel the click event by calling:



$("a #mylink").unbind('click');

      

0


source


jQuery is not stateful between post- callback events and does not remember the state of the button or the fact that the form was posted.

You need to store the state in a client side cookie or url attribute, but this is not the best solution.

I would handle this requirement from the server side (php, asp.net, etc.)

0


source


You can try the JQuery.one () function. The handler is executed at most once for each item.

http://api.jquery.com/one/

0


source







All Articles