JavaScript Add Dashes to phone numbers in forms ( Auto Hyphen Script)
Ok I am somewhat a novice when it comes to JavaScript. I just never really saw any reason to learn JavaScript. Then one day I was developing a form for a client and they said why am I getting thousands of blank emails? I quickly investigated the matter only to find that spam bots and automated sign up software running on a users machine was generating the redundant anoying emails. So what do you do to solve this problem? JavaScript to the rescue.
With JavaScript you can use a function to do almost anything you can think of. For the most part I use alot of JavaScript in my forms for validation and checking if fields are empty. However I recently found a task that no one on the internet seemed to know anything about. I wanted a form to add dashes to a phone number when a user clicked a button or blurred the element. So I wrote one and decided to share it with you. Here it is…
Basically what it does is takes the input of the field and stores it in a variable. I then start to break that variable into smaller variable. Those of you who have never programmed before. A variable is just a container for some value, property or other piece of information to be stored. So anywhay i then use the JavaScript command substr (short for sub string) example variable phone has the value of the phone number field stored in it. I want to create a new variable with the first three numbers of the field. How would I do that? Well this is where the command substr comes in to play. Simply define a new variable called areacode or whatever like so
var areacode = phone.substr(0,4);
Phone has a stored value of whatever the phone field data was. By using the substring command we grab the first three digits from that value. If the value was Hello World the new variable areacode would contain “Hel” . So if i only want the first three numbers why do I use 4 for the ending number? Well the last number is not used when indexing a substr command. So you would use the number immediatly after the one you wish to be last in your new variable. I then do that for the prefix and then of course the last four of the number. Once again I create a variable called final and define it like so…
var final = areacode + “-” + prefix + “-” lastfour;
What this does is simply take all the variables we made with all the pieces of information back together. You will notice the + “-” that adds in the dashes which are the real reason why I wrote this script in the first place.
Click here to download my JavaScript file to see the script.
- Javascript Objects Used
- subString();
- var
- Alert()