This snippet code allows you to block a double submit from the user. In this case, the normal behavior if no unique constraint check is done is that the record is created twice (or the number of times the user clicked on) on the database.
In my case, I have a contacts table. Creating a unique index on "First Name" + "Last Name" can block certain real situations (i.e. 2 employees have the same "First Name" + "Last Name"), so my solution is to disable the submission until the record is created. When the record takes some time to reply, the user tends to click again, submitting twice.
This code handles situations when you are using jQuery and jQuery.Validate
$("form").submit(function () {
$(":submit", this).attr("disabled", "disabled");
if (!$(this).valid()) {
// If not client-side valid, then re-enable button to a future validation
$(":submit", this).removeAttr("disabled");
return false;
}
return true;
});
The cool thing is you can reuse it for all the pages of your application, because it is generic enough to be in a Javascript file loaded in a master page.
No new comments are allowed on this post.
Discussion
Stephane Erard
Hey !
One step forward (I guess) :
When sending the form (using .ajaxForm() plugin), what I usually do, as I use the BlockUI plugin, is to .block() $(this) :) So user can see there is an interaction (xhr) and wait for it to complete.
Thanks ;)
labilbe
Interesting comment Stephane. The only drawback is you must ensure the classical POST and the Ajax POST end at the same location (Controller method). Some MVC frameworks distinguish both.
FroG
Hello, your approach can be extended outside JQuery, even not using any UI framework, using the "standard" disable attribute of the button: you start any action by disabling the button so that the user cannot click again, you perform all the Ajax calls you want, and at the end you enable again the button (if needed).
I think that's a good practice that should be shared to prevent the applications from click-maniacs.
labilbe
In fact I used it, because I add these multiple adds on my app.