I wrote this script a while back, it isn't the most efficient probably, JS isn't my strong suite.
<script language = "javascript">
function formatPhoneNumber(fld){
if (window.event.keyCode != 8){ //Ignore formatting if user is backspacing.
if (fld.value.charAt(fld.value.length-1) != "("){ //Allow the first instance of the open peren.
lastChar = fld.value.charAt(fld.value.length-1).replace(/\D*/, ''); //set a variable to the value of the last character in the string after replacing all non numeric chars.
if (lastChar == ""){ //remove the invalid character
fld.value = fld.value.substring(0, fld.value.length-1); //set the field to the correct data
}
}
if(fld.value.length == 1 && fld.value.charAt(fld.value.length-1) != "("){ //check to see if user already added the opening peren.
fld.value = "(" + fld.value; //If they didn't, add it for them.
}
if(fld.value.length == 4){ //Check to see if the area code is complete
fld.value = fld.value + ")"; //Add the closing peren after the area code.
}
if(fld.value.length == 8){ //Check to see if the prefix has been entered.
fld.value = fld.value + "-"; //If the prefix has been entered, insert the dash.
}
}
}
</script>
<form name = "phoneNumber">
<input type = "text" name = "phoneNumberToFormat" onkeyup = "formatPhoneNumber(this);">
</form>
Human beings, who are almost unique in having the ability to learn from the experience of others, are also remarkable for their apparent disinclination to do so.
-Douglas Adams (1952-2001)