Enter a phone number here:
<input type="text" id="phone" onkeypress="return numberPressed(event);" />
JavaScript
// Format the phone number as the user types it
document.getElementById('phone').addEventListener('keyup', function (evt) {
var phoneNumber = document.getElementById('phone');
var charCode = (evt.which) ? evt.which : evt.keyCode;
phoneNumber.value = phoneFormat(phoneNumber.value);
});
// We need to manually format the phone number on page load
document.getElementById('phone').value = phoneFormat(document.getElementById('phone').value);
// A function to determine if the pressed key is an integer
function numberPressed(evt) {
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57) && (charCode < 36 || charCode > 40)) {
return false;
}
return true;
}
// A function to format text to look like a phone number
function phoneFormat(input) {
// Strip all characters from the input except digits
input = input.replace(/\D/g, '');
// Trim the remaining input to ten characters, to preserve phone number format
input = input.substring(0, 10);
// Based upon the length of the string, we add formatting as necessary
var size = input.length;
if (size == 0) {
input = input;
} else if (size < 3) {
input = '(' + input.charAt(0) + input.charAt(1);
} else if (size < 6) {
input = '(' + input.charAt(0) + input.charAt(1) +input.charAt(2)+ ') ' + input.charAt(3) + input.charAt(4) + input.charAt(5);
} else if (size < 8) {
input = '(' + input.charAt(0) + input.charAt(1) + input.charAt(2)+') ' + input.charAt(3) + input.charAt(4) + input.charAt(5)+ ' - ' + input.charAt(6) + input.charAt(7);
} else {
input = '(' + input.charAt(0) + input.charAt(1) + input.charAt(2)+') ' + input.charAt(3) + input.charAt(4) + input.charAt(5) + ' - ' + input.charAt(6) + input.charAt(7) + ' - ' + input.charAt(8) + input.charAt(9);
}
return input;
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.