/ 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.
Expand |
Embed | Plain Text
<script type="text/javascript"> $(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 + "-"); } }); }); </script>
Comments
Subscribe to comments
You need to login to post a comment.

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
ha ha.. this is javascript—not php. It goes between tags in the head of your HTML document.
...between the <script%gt;</script%gt; tags...
i am fail. :(
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:
Using the $(this) keeps it from changing other inputs on the page.
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.