ProblemYou want to prevent visitors to your site from submitting a form more than once. SolutionAdd 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> DiscussionLike 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 seconds to return a result to the browser. Impatient web surfers (i.e., all of them) have the habit of clicking the submit button again and again in hopes of speeding up the process. But unlike other everyday thumb-twiddlers, multiple clicks on a web site form can create big headaches for you and your visitors. Often, the extra clicks lead to additional unwanted orders, and you'll be the one left to sort out the details of refunding the money your visitors did not intend to spend. First, the JavaScript defines a variable ordersent with a value of false. Then you create the function placeOrder( ), and on its first line use a conditional statement to check the value of ordersent. If it's TRue, the function will not be executed. The next three lines in the function submit the form, change its display value to "Please Wait…" (something web surfers will do grudgingly when explicitly told to do so), and disables the "Place Order" button, which prevents additional clicks from re-submitting the form. Finally, the function gives ordersent the value TRue, a second line of defense against additional clicks.
See AlsoOther JavaScript solutions for form-handling are covered in Recipes 7.1, 7.2, and 7.4. |