views:

448

answers:

4

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?

+1  A: 

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.

Joel Coehoorn
I would agree... but I'm trying to meet a customer's requirements.
Jason
Strange - customers usually don't require such specific things. If they're typing in a lot of numbers, maybe it's better to let them copy-paste into a bigger field, and parse that text?
Andrey Fedorov
I totally agree. Those phone formatters suck most of the time. Just deal with bad input on the server-side!
J-P
@jason: I empathize with you. I have a customer with the same requirements
Chris Lively
+3  A: 

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>
TStamper
A: 

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.

p.campbell
A: 

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-)

Yuval