Scenario:
You want your users to enter a phone or social security number with 3 separate web forms, but you don’t want the user to hit [Tab] to progress to the next form field. Have you ever noticed on some forms that as you type the numbers it automatically moves you to the next form box? Here’s a little javascript technique to achieve this functionality on your site.
Here’s an example:
Enter your phone:
Did you notice how as you entered your phone number it automatically moved to the next form field box for you?
Here’s how you can do this:
Add the following Javascript code below to the head of your site:
1 2 3 4 5 6 7 | <script type="text/javascript"> function autoFormAdvance(afterNumChars,currentFormId,nextFormId) { if(document.getElementById(currentFormId).value.length==afterNumChars) { document.getElementById(nextFormId).focus(); } } </script> |
The next step is to create your form elements. Each of these form elements must have an id attribute to identify them to the javascript.
Here’s an example of HTML code:
1 2 3 | <input type="text" onkeyup="autoFormAdvance(3,'areaCode','phonePre')" id="areaCode" maxlength="3" size="3"/> <input type="text" onkeyup="autoFormAdvance(3,'phonePre','phoneSuf')" id="phonePre" maxlength="3" size="3" /> <input type="text" id="phoneSuf" maxlength="4" size="4"/> |
If you notice in the code above, the autoFormAdvance function is being called upon an onKeyUp action for that form element.
There are 3 values the autoFormAdvance function takes:
Notice you don’t need to add the action on the last form element since, at this point, you’ve completed entering the data.
Further Suggestions: