Friday 23 October 2015

How to change format of mobile number in US format (XXX) XXX-XXXX using Jquery

Hi Everybody,

In this blog we will discuss about how to change format of mobile number in US format (XXX) XXX-XXXX using Jquery.

For this we have to code our Html and Jquery, given below

Html Code


<form id="example-form" name="my-form">
    <label>Phone number:</label><br />
    <!-- I used an input type of text here so browsers like Chrome do not display the spin box -->
    <input id="phone-number" name="phone-number" type="text" maxlength="14" placeholder="(XXX) XXX-XXXX" /><br /><br />
    <input type="button" value="Submit" />
</form>

Jquery Code

$('#phone-number', '#example-form')

.keydown(function (e) {
var key = e.charCode || e.keyCode || 0;
$phone = $(this);

// Auto-format- do not expose the mask as the user begins to type
if (key !== 8 && key !== 9) {
if ($phone.val().length === 4) {
$phone.val($phone.val() + ')');
}
if ($phone.val().length === 5) {
$phone.val($phone.val() + ' ');
}
if ($phone.val().length === 9) {
$phone.val($phone.val() + '-');
}
}

// Allow numeric (and tab, backspace, delete) keys only
return (key == 8 || 
key == 9 ||
key == 46 ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
})
.bind('focus click', function () {
$phone = $(this);
if ($phone.val().length === 0) {
$phone.val('(');
}
else {
var val = $phone.val();
$phone.val('').val(val); // Ensure cursor remains at the end
}
})
.blur(function () {
$phone = $(this);
if ($phone.val() === '(') {
$phone.val('');
}
});

Note:-After change mobile number in this format, best practice is this you have to save only 10 digit mobile number in your database(without (, ), and space).

For this if your server side script written in php then use below code to convert this US format mobile number to simple 10 digit number(for save in database) .

PHP Code

preg_replace("/[^0-9]/","",$mobile)

here $mobile is mobile input field you receive by Get or Post method after submit this form.

Thanks for read this blog, if you any question or suggestion please type in comment box.

No comments:

Post a Comment