最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Format Text Going Into A Textbox for a Phone Number, etc - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a ment  | 

3 Answers 3

Reset to default 5

I 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/

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论