Created
April 4, 2022 19:53
-
-
Save clandestine8/819afed6976457ed98f5d208461c5cc8 to your computer and use it in GitHub Desktop.
Auto Format North American Phone Numbers in HTML Forms using Vanilla JS
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
document.addEventListener('DOMContentLoaded', function() { | |
let tels = document.querySelectorAll('input[type=tel]'); | |
tels.forEach(function (tel) { | |
if (tel) { | |
tel.addEventListener('change', function () { | |
let inputField = this | |
inputField.value = formatPhoneNumber(inputField.value); | |
}); | |
tel.addEventListener('keyup', function () { | |
let inputField = this | |
inputField.value = formatPhoneNumber(inputField.value); | |
}); | |
} | |
}) | |
}, false); | |
window.formatPhoneNumber = function (value) { | |
if (!value) return value; | |
const phoneNumber = value.replace(/[^\d]/g, ''); | |
const phoneNumberLength = phoneNumber.length; | |
if (phoneNumberLength < 4) return phoneNumber; | |
if (phoneNumberLength < 7) { | |
return `(${phoneNumber.slice(0, 3)}) ${phoneNumber.slice(3)}`; | |
} | |
return `(${phoneNumber.slice(0, 3)}) ${phoneNumber.slice( | |
3, | |
6 | |
)}-${phoneNumber.slice(6, 10)}`; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment