How can I format the input phone number using jQuery?
When trying to format a phone number[e.g. (xxx) xxx-xxxx], it can be challenging to find the proper solution. In my case, I found an effective solution for phone number formatting. And I’m utilizing the onInput event on the HTML input tag to invoke the JQuery function. Within this JQuery function, there are three key features.
- Accept only integers and restrict any special characters or strings.
- There is a length limit; we cannot exceed the length.
- We have the flexibility to format the number as we want. Like: (xxx) xxx-xxxx or xxx-xxx-xxxx
HTML
<input type="tel" name="phone" value="" onInput="this.value = phoneFormat( this.value )">
JQuery
function phoneFormat( input ){//returns (###) ###-####
input = input.replace( /\D/g, '' ).substring( 0, 10 ); //Strip everything but 1st 10 digits
var size = input.length;
if( size > 0 ){ input = "(" + input }
if( size > 3 ){ input = input.slice( 0, 4 ) + ") "+ input.slice( 4 ) }
if( size > 6 ){ input = input.slice( 0, 9 ) + "-" + input.slice( 9 ) }
return input;
}
Window OnLoad
If we have a predefined phone number and we want to format it on page load, we can use the following example.
$( "input[ type = tel ]" ).each( function( e ){
$( this ).val( phoneFormat( $( this ).val( ) ) );
} );
Note: I’m using jQuery v3.3.1
7 Comments
Michaelskali
January 21, 2025thanks, interesting read
_________________
Best online casino
Arun Giri
February 8, 2025Thank You
JamesSmade
January 22, 2025Cool + for the post
_________________
Top online casino
Arun Giri
February 8, 2025Thank You
Athena
February 6, 2025Awesome post.
Arun Giri
February 8, 2025Thank You