Click here to Skip to main content
15,885,662 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
HTML form submission. When clicking on the submit button I want the button to show that it has been clicked and is waiting for the server (which may take 10+ seconds), and prevent the user from resubmiting.

Just disabling the button on click has a potential problem in that in case something goes wrong, the user won't be able to try again because the button is disabled - e.g. if the action page shows an error, and they go back to the form, they can't submit because the button will still be disabled.

I'm aware that disabling and reenabling the button is not a fool proof solution to prevent double submissions, but it's sufficient in my case.

I don't want to use AJAX. I can use Jquery.

What I have tried:

Below is my code.

Problems:
- The form doesn't submit. I don't know why.
- The form doesn't validate. If a required input is not filled, there will be no visual indication like the default for HTML/browsers.
- Even if it does submit, will it actually start submit immediately, and simultaneously wait for the server to respond (like I want), or can I possibly end up with a silly solution where the timer doesn't run at the same time as the server is processing, making it completely useless?


<form action="somepage.html">
..some more inputs here...
<input id="submit-button" onclick="submitClicked();" class="btn" type="submit" name="submit" value="Submit"/>
</form>


function submitClicked() {
        var btn = $('#submit-button');
        btn.prop('disabled', true);
        btn.prop("value", "Wait...");

        setTimeout(function() {
            btn.prop("value", "Try again?");
            btn.prop('disabled', false);
        }, 15000);
}
Posted
Updated 31-Aug-21 22:37pm

1 solution

You need to disable the button after the form has been submitted. Use another setTimeout to do that:
JavaScript
function submitClicked(){
    setTimeout(function(){
        $("#submit-button").prop("disabled", true).val("Wait...");
    }, 100);
    
    setTimeout(function(){
        $("#submit-button").prop("disabled", false).val("Try again?");
    }, 15000);
}
 
Share this answer
 
Comments
Jame_T 1-Sep-21 14:34pm    
Thanks! That seems to work, except the whole function will still run if input validation fails (a required inpout is not filled). Meaning, the button still will get disabled, while the browser focuses the input and says its required.
Any workaround for that?
Richard Deeming 2-Sep-21 3:41am    
Check that the form is valid before disabling the button. For example, using the reportValidity method:
HTMLFormElement.reportValidity() - Web APIs | MDN[^]

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900