-
-
Save royce002/8a21c933bf57f4fddc1e9dc1c753902a to your computer and use it in GitHub Desktop.
JS Phone Number Formatter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*** PHONE NUMBER FORMATTER ***/ | |
function phoneFormat(input) { | |
// Strip all characters except digits | |
input = input.replace(/\D/g, ''); | |
// Trim input to ten characters, to preserve phone format | |
input = input.substring(0, 10); | |
// Format string based on length | |
var size = input.length; | |
if (size == 0) { | |
input = input; | |
} else if (size < 3) { | |
input = '(' + input; | |
} else if (size < 6) { | |
input = '(' + input.substring(0, 3) + ') ' + input.substring(3, 6); | |
} else { | |
input = '(' + input.substring(0, 3) + ') ' + input.substring(3, 6) + '-' + input.substring(6, 10); | |
} | |
return input; | |
} | |
// KEY BINDING | |
document.getElementById('eventContactPhone').addEventListener('keyup', function(evt) { | |
var phoneNumber = document.getElementById('eventContactPhone'); | |
var charCode = (evt.which) ? evt.which : evt.keyCode; | |
phoneNumber.value = phoneFormat(phoneNumber.value); | |
}); | |
//Before Submit document.getElementById('eventContactPhone').value.replace(/\D/g,''); | |
/*** PHONE NUMBER FORMATTER ***/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment