I have a button that I would like to disable when the form submits to prevent the user submitting multiple times.
I have tried naively disabling the button with javascript onclick but then if a client side validation that fails the button remains disabled.
How do I disable the button when the form successfully submits not just when the user clicks?
This is an ASP.NET form so I would like to hook in nicely with the asp.net ajax page lifecycle if possible.
Not sure if this will help, but there's onsubmit event in form. You can use this event whenever the form submit (from any button or controls). For reference: http://www.htmlcodetutorial.com/forms/_FORM_onSubmit.html
Note that rp's approach will double submit your form if you are using buttons with
UseSubmitBehavior="false"
.I use the following variation of rp's code:
A solution will be to set a hidden field when the button is clicked, with the number 1.
On the button click handler first thing is to check that number if it is something other than 1 just return out of the function.
The following function is useful without needing the disabling part which tends to be unreliable. Just use "return check_submit();" as part of the onclick handler of the submit buttons.
There should also be a hidden field to hold the form_submitted initial value of 0;
You may also be able to take advantage of the onsubmit() javascript event that is available on forms. This event fires when the form is actually submit and shouldn't trap until after the validation is complete.
The correct (as far as user-friendliness is concerned, at least) way would be to disable the button using the OnClientClick attribute, perform the client-side validation, and then use the result of that to continue or re-enable the button.
Of course, you should ALSO write server-side code for this, as you cannot rely on the validation even being carried out due to a lack, or particular implementation, of JavaScript. However, if you rely on the server controlling the button's enabled / disabled state, then you basically have no way of blocking the user submitting the form multiple times anyway. For this reason you should have some kind of logic to detect multiple submissions from the same user in a short time period (identical values from the same Session, for example).