8.6. Disabling a Form Submit Button After the First Click
Problem
You want to prevent visitors to your site from submitting a form more than once.
Solution
Add a JavaScript function to your form that submits the form, and then disables the submit button and changes its display value after the user clicks it.
This code goes in the <head>
section of your web page
code:
<script type="text/javascript" language="JavaScript"> var ordersent = false; function placeOrder() { if(ordersent == true) { return; } document.orderform.submit(); document.orderform.orderbtn.value = 'Please Wait…'; document.orderform.orderbtn.disabled = true; ordersent = true; } </script>
Then, to ensure that the form works on browsers with JavaScript
disabled, write the function-calling button on the page with the
document.write()
method and place
the non-JavaScript button inside a <noscript>
tag. The code for the form
and buttons looks like this:
<form name="orderform" method="post" action="/cgi-bin/order.cgi"> <script type="text/javascript" language="JavaScript"> <!-- document.write('<input type="button" name="orderbtn" value="Place Order" onclick="return placeOrder();">'); //--> </script> <noscript> <input type="submit" value="Place Order"> </noscript> </form>
Discussion
Like elevator call buttons and watched pots on stovetops, web forms do not respond more quickly when given extra attention. When connecting to a credit card gateway (or to any other server over a slow Internet connection), web forms often take several ...
Get Web Site Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.