In this example, you can click the first button as many times as you want. In practice this can cause a form to be submitted, or some other event triggered, more than once. The second button however will only accept a single click and ignore all subsequent clicks.
The trick is to use JavaScript to set the disabled property of the button to true. The disabled property was first introduced by Microsoft but has since been adopted as a standard by the W3C.
For a simple form, with no associated JavaScripts, you can use:
<form method="POST" action="..." onsubmit="myButton.disabled = true; return true;"> ... <input type="submit" name="myButton" value="Submit"> </form>
So when the form is submitted – either by clicking on the submit button or pressing Enter in a text input field – the submit button will be disabled to prevent double-clicking.
If you’re already using JavaScript form validation then the command can instead be added to the script as follows:
<form method="POST" action="..." onsubmit="return checkForm(this);"> ... <input type="submit" name="myButton" value="Submit"> </form> <script type="text/javascript"> function checkForm(form) { // // validate form fields // form.myButton.disabled = true; return true; } </script>
Rather than simply disabling the button, we can also change the text so that people don’t get confused. This example first disables the button and then changes the label from “Submit” to “Please wait…”.
The code executed when the form is submitted includes the following:
<script type="text/javascript"> function checkForm(form) // Submit button clicked { // // check form input values // form.myButton.disabled = true; form.myButton.value = "Please wait..."; return true; } function resetForm(form) // Reset button clicked { form.myButton.disabled = false; form.myButton.value = "Submit"; } </script>