Code snippet for an input field for a phone number that auto-formats:
var phoneNum = document.createElement('input');
phoneNum.setAttribute("oninput", "onInputPhoneNum()");
var phoneNumPrevLength = 0;
String.prototype.splice = function(start, delCount, newSubStr) {
return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
};
function onInputPhoneNum() {
var x = phoneNum.value;
if(x.length >= 3 && phoneNumPrevLength <= 2)
{
x = x.splice(0, 0, "(");
x = x.splice(4, 0, ") ");
}
if(x.length <= 5 && phoneNumPrevLength >= 6)
{
x = x.substring(1, 3);
}
if(x.length >= 9 && phoneNumPrevLength <= 8)
{
x = x.splice(9, 0, "-");
}
if(x.length <= 9 && phoneNumPrevLength >= 10)
{
x = x.substring(0, 8, "-");
}
if(x.length > 14)
{
x = x.substring(0, 14);
}
phoneNumPrevLength = x.length;
phoneNum.value = x;
}