Posted By

xtheonex on 01/27/09


Tagged

javascript jquery


Versions (?)

Who likes this?

13 people have marked this snippet as a favorite

jamesming
rickfu
bryandease
enajenkins
umang_nine
gtalmes
kikuchiyosesa
gvisitac
jasonevers
technopoetic
sethetter
Kurt
ringo380


jQuery snippet to convert numbers into US phone number format as they're typed


 / Published in: jQuery
 

This little piece of code will convert to US phone format, as typed. Eg, As the number "0000000000" was typed, it would convert it to (000)-000-0000.

  1. <script type="text/javascript">
  2. $(function() {
  3. $("input[@name='phone']").keyup(function() {
  4. var curchr = this.value.length;
  5. var curval = $(this).val();
  6. if (curchr == 3) {
  7. $("input[@name='phone']").val("(" + curval + ")" + "-");
  8. } else if (curchr == 9) {
  9. $("input[@name='phone']").val(curval + "-");
  10. }
  11. });
  12. });
  13. </script>

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: gvisitac on January 17, 2010

Hello, I am trying to use your code for my test form and I can't get it to work. Can you please tell me where this code should be in my .php file.

I've tried before this line:

I've tried before the

and I've tried inside the form tags without any success to get it to work.

Can you please suggest where, exactly, this should be?

Here's my code for a test form:

$(function() { $("input[@name='phone']").keyup(function() { var curchr = this.value.length; var curval = $(this).val(); if (curchr == 3) { $("input[@name='phone']").val("(" + curval + ")" + "-"); } else if (curchr == 9) { $("input[@name='phone']").val(curval + "-"); } }); });

Untitled Document

Posted By: rewdy on February 11, 2011

ha ha.. this is javascript—not php. It goes between tags in the head of your HTML document.

Posted By: rewdy on February 11, 2011

...between the <script%gt;</script%gt; tags...

Posted By: rewdy on February 11, 2011

i am fail. :(

Posted By: jcc2010 on December 20, 2011

Just a little improvement, take it if you like:

HTML5 has the input type=tel form element now, so you can do something like this:

$("input[type='tel']").keyup(function() {
    var curchr = this.value.length;
    var curval = $(this).val();
    if (curchr == 3) {
        $(this).val("(" + curval + ")" + "-");
    } else if (curchr == 9) {
        $(this).val(curval + "-");
    }
});

Using the $(this) keeps it from changing other inputs on the page.

Posted By: bas3pix on November 17, 2012

Hi guys, maybe this script can help further improve your script: http://www.deltadeveloper.nl/fragmenten/telephone-number-formatting-script. It really helped us in formatting telephone numbers. Hopelfully it can be of great use for your guys or any of your visitors.

You need to login to post a comment.