Ken
Ken

Reputation: 21

Stop onClick from firing twice using jQuery

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

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

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

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

but that doesn't work. I also tried

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

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

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

Upvotes: 2

Views: 8420

Answers (4)

Cornel Urian
Cornel Urian

Reputation: 396

You can try Jquery .one() function. The handler is executed at most once per element.

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

Upvotes: 0

Russ Cam
Russ Cam

Reputation: 125538

using one() would remove the event handler after the first time the <a> link is clicked.

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

or you could define the click event using jQuery, then remove using jQuery too (but this is essentially what using one() does anyway).

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

If you're sticking with the onclick attribute inline, then 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 has pointed out, this change is client-side and so will not be persisted across page refreshes. You would need to come up with some mechanism to persist the change if that is what you need. Most web frameworks have a mechanism to do this

Upvotes: 14

Mark
Mark

Reputation: 6081

jQuery is not stateful between post-back events and will not remember button state or the fact that the form has been posted.

You would need to save 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)

Upvotes: 0

Nathan Taylor
Nathan Taylor

Reputation: 24606

You can unbind the click event by calling:

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

Upvotes: 0

Related Questions