Skip to content

Instantly share code, notes, and snippets.

@louisesalas
Created October 18, 2023 15:34
Show Gist options
  • Save louisesalas/941a6d34073f619a0b0f2034071525b3 to your computer and use it in GitHub Desktop.
Save louisesalas/941a6d34073f619a0b0f2034071525b3 to your computer and use it in GitHub Desktop.
Format phone input with country code
// pretty-format phone inputs
( function( $ ) {
$(function() {
$('.gform_wrapper').on('input','[type="tel"]' , function (){
var phoneNumber = $(this).val();
// Remove Non numeric input
var numericPhoneNumber = phoneNumber.replace(/\D/g, '');
var digitsBeforeLast10 = '';
if(numericPhoneNumber.length > 10) { //Check if the digits are greater than 10 then include country code in the format
digitsBeforeLast10 = '+'+numericPhoneNumber.slice(-12, -10); // GET the digits before the last 10 digits and will serve as the country code ex : +1
}
// Get the last 10 digits of the number in the input
var last10Digits = numericPhoneNumber.slice(-10);
//Format the number with the country code ex : +1 (111) 111-1111
var s = "";
last10Digits.length
? ((s = "(" + last10Digits.substr(0, 3)),
last10Digits.length >= 3 && (3 != last10Digits.length ) && (s += ") "), // format the first 3 digits as (XXX)
(s += last10Digits.substr(3, 3)),
last10Digits.length >= 6 && (6 != last10Digits.length ) && (s += "-"), // format the next 3 digits as XXX-
(s += last10Digits.substr(6, 4))) // get the last 4 digits XXXX
: 1 == e.length && "(" == e[0] && (s = "("),
$(this).val(digitsBeforeLast10 + ' ' + s); // format number as +X (XXX) XXX-XXXX
});
})
})( jQuery );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment