Stupid Form Tricks - Formatting Phone Numbers With Javascript
for most browsers
This script will put a phone number into this format - (xxx)xxx-xxxx
It also contains the code for this format - xxx-xxx-xxxx
You can easily switch formats by commenting out and uncommenting the marked areas of the script.
The script can format any number of phone number fields. You just need to name each field as an item in the nums array.
Home Work <script language="javascript"> var nums=new Array('document.forms[0].phone1', 'document.forms[0].phone2'); function doThis(){ var re= /\D/; // test for this format: (xxx)xxx-xxxx var re2 = /^\({1}\d{3}\)\d{3}-\d{4}/; // test for this format: xxx-xxx-xxxx //var re2 = /^\d{3}-\d{3}-\d{4}/; for (i=0; i<nums.length;i++){ var num=eval(nums[i]+'.value'); var newNum; if (num != "" && re2.test(num)!=true){ if (num != ""){ while (re.test(num)){ num = num.replace(re,""); } } if (num.length != 10){ alert('Please enter a 10 digit phone number'); eval(nums[i]).select(); break; } else { // for format (xxx)xxx-xxxx newNum = '(' + num.substring(0,3) + ')' + num.substring(3,6) + '-' + num.substring(6,10); // for format xxx-xxx-xxxx // newNum = num.substring(0,3) + '-' + num.substring(3,6) + '-' + num.substring(6,10); eval(nums[i]).value=newNum; } } } } </script>
PXL8 2003