I am having problem that when i am trying to submit the form by clicking on the submit button it takes some time to post request during this if i am again click on the Submi
One solution is to not use an <input>
as the submit button, but instead a <div>
(or <span>
) styled as a button, having an onclick
attribute:
<form method="post" id="my-form">
<input type="text" name="input1">
<input type="text" name="input2">
<input type="text" name="input3">
...
<div class="button" id="submit-button" onclick="submitOnce()">
Submit
</div>
</form>
And the submitOnce
function would first remove the onclick
attribute and then submit the form:
function submitOnce() {
document.getElementById('submit-button').removeAttribute('onclick');
document.getElementById('my-form').submit();
}
I love the simplicity and directness of Zoidberg's answer.
But if you want to hook up that handler using code rather than markup (some people prefer to keep markup and code completely separated), here it is using Prototype:
document.observe('dom:loaded', pageLoad);
function pageLoad() {
var btn;
btn = $('idOfButton'); // Or using other ways to get the button reference
btn.observe('click', disableOnClick);
}
function disableOnClick() {
this.disabled = true;
}
or you could use anonymous functions (I'm not a fan of them):
document.observe('dom:loaded', function() {
var btn;
btn = $('idOfButton'); // Or using other ways to get the button reference
btn.observe('click', function() {
this.disabled = true;
});
});
Doing it using jQuery will look very similar.
Disabling the button is one solution, but potentially poses a problem for keyboard users who just hit enter to submit a form. In this scenario, the button won't be disabled. The sure-fire method would be to handle the onsubmit
event like so:
(function () {
var allowSubmit = true;
frm.onsubmit = function () {
if (allowSubmit)
allowSubmit = false;
else
return false;
}
})();
(well, as sure-fire as you can get with JS enabled anyway). You could disabled the button as a visual confirmation to the end user that the form can only be submit once too.