What JavaScript should I use for a telephone number entry in a webpage?
-
22-08-2019 - |
Question
I have three input boxes for entering a telephone number on a webpage:
XXX XXX XXXX
I need JavaScript that moves the user between the boxes as you type. After the third character, it moves you to the second box, etc...
In the past, I've had trouble with the backspace. When I clicked backspace from the second box, it puts me in the first, but then shoots me back to the second.
What is the best way to do this?
Solution
You should use jQuery AutoTab
Example code like this
<div><strong>Phone Number:</strong></div>
<input type="text" name="area_code" id="area_code" maxlength="3" size="3" /> -
<input type="text" name="number1" id="number1" maxlength="3" size="3" /> -
<input type="text" name="number2" id="number2" maxlength="4" size="5" />
<script type="text/javascript">
$(document).ready(function() {
$('#area_code').autotab({ target: 'number1', format: 'numeric' });
$('#number1').autotab({ target: 'number2', format: 'numeric', previous: 'area_code' });
$('#number2').autotab({ previous: 'number1', format: 'numeric' });
});
</script>
OTHER TIPS
Personally, I'd just accept almost anything and worry about re-formatting it server-side. I've had to use so many bad javascript phone formatters that I'm not a big fan.
I'd suggest going with this one-box solution instead of the three. It relieves so many headaches and edge cases of bouncing between boxes, and having the first box do a .select()
, and then the user hits delete, and wipes their entry away. Yucky.
http://javascript.internet.com/forms/format-phone-number.html
All the autoformatting you could want. Of course, this is the North American standard, and you'd have to modify this for RestOfTheWorld.
I'd use a key listener to check for typing when the first field has focus, count the number of characters already typed, and if enough characters have been typed, move the focus to the second field, and so on.
Hope this helps,
Yuval =8-)