Couldn't find this anywhere, maybe I'm looking for the wrong verbs.
I'm trying to get a textbox to require a certain format as you type in a number. For simplicity, lets use a phone number example. As I type into the box I want some guidelines to help the user enter the correct format of the phone number:
(4__) ___-____
(403) 3__-____
(403) 329-98__
(403) 329-9824
This will prevent users from forgetting the area code, etc. I've seen this done elsewhere but am unsure of where to start.
I'm sure this is javascript but it's for a ruby on rails app so if you know of a plugin or something.
Thanks!
Josh
Couldn't find this anywhere, maybe I'm looking for the wrong verbs.
I'm trying to get a textbox to require a certain format as you type in a number. For simplicity, lets use a phone number example. As I type into the box I want some guidelines to help the user enter the correct format of the phone number:
(4__) ___-____
(403) 3__-____
(403) 329-98__
(403) 329-9824
This will prevent users from forgetting the area code, etc. I've seen this done elsewhere but am unsure of where to start.
I'm sure this is javascript but it's for a ruby on rails app so if you know of a plugin or something.
Thanks!
Josh
Share Improve this question asked Oct 1, 2010 at 14:58 Joshua PinterJoshua Pinter 47.6k23 gold badges258 silver badges255 bronze badges3 Answers
Reset to default 5I think you are looking for the masked input jQuery plugin
Why not just create three text inputs, and use javascript to move focus between them as they are filled?
For an example, see this jsfiddle. It uses a quick, vanilla-JS function to advance between the inputs:
function advance_phone(event, next_element)
{
var evt = event ? event : window.event; // Older versions of IE don't pass along an event object
var target = evt.target || evt.srcElement; // Get the target of the event
if (target.value.length == target.maxLength)
{
document.getElementById(next_element).focus();
}
}
You take this further and enhance it to allow moving backwards between boxes when backspace is pressed and add a keypress handler to restrict allowed keys to numbers. Or you could even style the inputs so that it looks like a phone field.
+1 to Amit's suggestion.
However, since you're using Rails you might want something dependent on Prototype instead of jQuery. Check this out http://www.xaprb./blog/2006/11/02/how-to-create-input-masks-in-html/