I am dealing with a legacy application where they use [a] tags for many Ajax form "submits". If we were using [input] buttons we could just set the disable attribute of the [input] tag. But on hyperlinks disable is not part of the spec and is not consistent cross-browser.
We are looking for a simple solution for blocking the extra clicks on a hyperlink.
Note: we are using JavaScript with jQuery
womp's solution is a very very thorough way to go about this.
However, if you want something a little simpler, I would probably implement a semaphore. Simply set a "submitting" flag, and test to see if the semaphore is set when the user clicks the link. You can do this by setting the flag on the DOM object itself, or use a global boolean.
$('#link').each(function() {
this.submitting = false;
}).click(function() {
if (!this.submitting)
{
this.submitting = true;
var self = this;
$.ajax({
success: function() {
self.submitting = false;
},
error: function() {
self.submitting = false; // make sure they can try again
}
});
}
});
I've obviously shortened the $.ajax call, but I think you get the point.
Edit: Er... actually, forgot the most important part. The if (!submitting).
In your "click" handler either return false or prevent default -
$('#target').click(function(e) {
e.preventDefault();
alert('Handler for .click() called.');
});
$('#target').click(function(e) {
alert('Handler for .click() called.');
return false;
});
Hmm... to only allow the button to be pressed once (throughout the life of the page) then maybe utilize .data() -
http://api.jquery.com/data/
Or toggle an attribute.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With