Senthil Sivaramakrishnan Senthil Sivaramakrishnan -4 years ago 237
Javascript Question

Auto Format Phone Number in Jquery

I have one textbox for phone number. My phone number should be XXX-XXX-XXX like this format.

I got the solution for XXX-XXX-XXX format, but i don't know how to modify that code.

$('#ssn').keyup(function() {
var val = this.value.replace(/\D/g, '');
var newVal = '';
while (val.length > 3) {
newVal += val.substr(0, 3) + '-';
val = val.substr(3);
newVal += val;
this.value = newVal;

Answer Source

Since you're using jQuery you can try jquery masked-input-plugin.

There's a jsFiddle for you here where you can see how it works.

The source code for the project on GitHub can be found here.

The implementation is more than simple:


<input id="ssn"/>




Another good one can be found here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download