There has been always one troubling issue regarding web forms and user interaction: when the user double clicks the submit button. Detecting and preventing it or disabling the button is an expensive operation in terms of computing. Fortunately, jQuery has a neat solution. As usual.
Enter one function. This function will simply unbind the click event from an object after it has been clicked. It is really that simple. All you need to pass to one() is the event that you want to bind/unbind and a handler function to execute when the event is triggered:
[js]
jQuery(‘#submit-form’).one(‘click’, function() {
alert(‘Hold your horses, girl!’);
});
[/js]
or you can simply hide the button, like the following example
The code for the example above is
[js]
jQuery(document).ready(function(){
jQuery(‘#oncebutton’).one(‘click’, function() {
jQuery(this).slideUp();
});
});
[/js]
Read more about one() in the documentation for jQuery.
Nice tut..important piece of information..thanks..
I’m using chrome and the alert never shows for the first example.
Vinny, remember to wrap the function with
jQuery(document).ready(function(){
//code goes here
});
as shown in the second snippet.
Just in case, the first image isn’t an working example, ok? it’s merely illustrative.
Ah but what happens if they’re submitting a form that errors? They’ll need to resubmit but the button will have no click event anymore
Of course Jenna, but this is only an example. You could disable the button before validation, and if there are errors you could enable click again. However, you could also validate the form while it’s being filled using, for example, the Validation plugin for jQuery.
全是英文,看不懂。
是的防守对方士大夫士大夫撒的撒的士大夫撒的发生的撒的撒的撒的撒的撒的ss地方s的
士大夫
sdf sdf
撒的
士大夫
撒的f撒的
撒的
士大夫
士大夫
士大夫
士大夫
士大夫
Hey
This does the same thing as unbind(‘click’); but i have a problem here… say you do one() or unbind the click… then if you try to do toggle or slideToggle() it wont work any more… very fustrating.. then if you do a unbind() then a bind() you get a jQuery Internal error .. this has wasted my day.. not your post.. but this stupid click crap
Ricky, the jQuery API docs have an example in this page
http://api.jquery.com/unbind/
(the one with a yellow button and two buttons) to continuously bind and unbind the event.
[…] the topHow to avoid double clicking with jQuery I could of done with this article a month ago!Click here to visit the article »About the author… Stu Greenham is a Web Designer / Developer who lives in Hull (North East […]
Yes correct. But we cannot use this option for while submitting the form(with validation)
Very nice, you have saved me a few hours for sure. Good job