views:

40

answers:

3

Hi There,

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

+3  A: 

I think you are looking for the masked input jQuery plugin

Amit
Anyway to get this to work with Prototype so I don't have to include the jQuery library?
Josh Pinter
There is a prototype version at http://github.com/bjartekv/MaskedInput
Amit
A: 

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.

Daniel Vandersluis
A: 

+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.com/blog/2006/11/02/how-to-create-input-masks-in-html/

StefanO