Disabling the submit button is indeed the way to go.
However, in a lot of cases the server side logic to be executed depends on the presence of the name-value pair of the submit button in question in the request parameter map. Especially in server side component based MVC frameworks like MS ASP.NET and Sun JSF, but also in "simple" forms having more than one submit button. The name-value pair of the pressed submit button is mandatory to determine the action to be executed. Disabling the button would make its name-value pair to completely disappear in the request parameter map and the server side may not take any action or execute the wrong action.
There are basically 2 ways to go around this:
Use setTimeout()
to disable the button after a few milliseconds so that its name-value pair get sent anyway. 50ms is an affordable amount.
$("form").submit(function() {
var form = this;
setTimeout(function() {
$(':submit', form).attr('disabled', true);
}, 50);
});
Copy the name-value pair of the actually pressed submit button into a hidden input of the form. This is a bit trickier since this information isn't available in the submit
event of the <form>
. You need to let the $(document)
capture the last clicked element.
$("form").submit(function() {
$(':submit', this).attr('disabled', true);
$(this).append($('<input/>').attr({
type: 'hidden',
name: $.lastClicked.name,
value: $.lastClicked.value
}));
});
$(document).click(function(e) {
e = e || event;
$.lastClicked = e.target || e.srcElement;
});
Update: as per your update:
Well, I see some of the advice said disabling the submit button. This should prevent the from submit multiple times, but the problem is the form element in my page isn't refreshed, if I disable it the user won't be able to submit it anymore, disabling it for 15s may work, but is this the right way to solve this problem ?
So you're actually firing an ajaxical request. You could just re-enable the button(s) in the callback handler of the jQuery's ajax function. Assuming you're using jQuery.post
:
$("form").submit(function() {
// Disable buttons here whatever way you want.
var form = this;
$.post('some/url', function(data) {
// Re-enable buttons at end of the callback handler.
$(':submit', form).attr('disabled', false);
});
});