Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript dashes in phone number

Tags:

javascript

I tried to research the answer to this question but I'm lost. I am trying to make a one search bar that automatically puts a dash in the phone number. I've solved that.

The next part is the challenging part. How can I make it always do XXX-XXX-XXXX, even if the characters pasted were something like 555 555 1212 or 555---555-1212, where it will only reel back the number and output with 555-555-1212. It shouldn't count the spaces or extra dashes as a character.

I found: http://www.jotform.com/answers/15202-can-I-add-script-to-my-form-that-will-automatically-add-hyphens-in-between-the-3-digit-area-code-and-also-the-3-digit-prefix

I changed it just a bit by adding:

<SCRIPT LANGUAGE="JavaScript">
        function addDashes(f)
            {
                f.value = f.value.slice(0,3)+"-"+f.value.slice(3,6)+"-"+f.value.slice(6,15);
            }
    </SCRIPT>


<input id="input_4" class="form-textbox" maxlength="15" name="atn" size="25" onBlur='addDashes(this)' />

Right now, this works only if the user puts 5555555555 and automatically turns it into 555-555-5555. I'm trying to figure out how to take something like 5-55555-5555 and turn it into 555-555-5555. Currently, it makes it 5-5-555-5-5555.

See my dilemma? lol. It can't be php or any server side scripting as this must be able to run on a desktop.


Resolution:

<SCRIPT LANGUAGE="JavaScript">
        function addDashes(f)
            {
                f.value = f.value.replace(/\D/g, '');

                f.value = f.value.slice(0,3)+"-"+f.value.slice(3,6)+"-"+f.value.slice(6,15);
            }
    </SCRIPT>
like image 807
traveler84 Avatar asked Oct 26 '12 19:10

traveler84


2 Answers

First, clean your input by deleting all chars that are not numbers (ref.: Regex to replace everything except numbers and a decimal point)

Then, you put your dashes.

function addDashes(f)
{
    f_val = f.value.replace(/\D[^\.]/g, "");
    f.value = f_val.slice(0,3)+"-"+f_val.slice(3,6)+"-"+f_val.slice(6);
}
like image 147
Matheus Azevedo Avatar answered Sep 29 '22 04:09

Matheus Azevedo


I have a strong tendency to treat phone numbers as a straight string of 10 digits with no formatting (so I can apply formatting to them on-the-fly, as needed and so searching and comparison is simpler), although that may change if I ever have to deal with international phone numbers. If all you're dealing with is US phone numbers, this will work nicely (formats it as it's typed):

function addDashes(f) {
    var r = /(\D+)/g,
        npa = '',
        nxx = '',
        last4 = '';
    f.value = f.value.replace(r, '');
    npa = f.value.substr(0, 3);
    nxx = f.value.substr(3, 3);
    last4 = f.value.substr(6, 4);
    f.value = npa + '-' + nxx + '-' + last4;
}​

Here's a fiddle: http://jsfiddle.net/EYuk5/

like image 37
pete Avatar answered Sep 29 '22 05:09

pete