<![CDATA[
var $ = jQuery;
String locale = getUserLocale();
$(document).ready(function() {
if (!isEmptyNull(locale) && locale.equals("zh_CN")) {
$("input[id*='text12']").mask('9999年99月99日');
}
else {
$("input[id*='text12']").mask('99/99/9999');
}
});
]]>
<p:calendar id="text12" styleClass="calendar" maxlength="10" pattern="#
{pc_Test.dateDisplayFormat}"></p:calendar>
If the locale is equal to 'zh_CN', the masking would be '9999年99月99日'. Otherwise, it would would be '99/99/9999'.
When I remove the if else command, it works. But if I put the if else command inside, it doesn't work.
How do I solve it?
Check out the below code..
<input
type="text"
name="date"
placeholder="dd/mm/yyyy"
onkeyup="
var v = this.value;
if (v.match(/^\d{2}$/) !== null) {
this.value = v + '/';
} else if (v.match(/^\d{2}\/\d{2}$/) !== null) {
this.value = v + '/';
}"
maxlength="10"
>
<input
type="text"
name="date"
placeholder="mm/dd/yyyy"
onkeyup="
var v = this.value;
if (v.match(/^\d{2}$/) !== null) {
this.value = v + '/';
} else if (v.match(/^\d{2}\/\d{2}$/) !== null) {
this.value = v + '/';
}"
maxlength="10"
>
<input
type="text"
name="date"
placeholder="yyyy/mm/dd"
onkeyup="
var v = this.value;
if (v.match(/^\d{4}$/) !== null) {
this.value = v + '/';
} else if (v.match(/^\d{4}\/\d{2}$/) !== null) {
this.value = v + '/';
}"
maxlength="10"
>
<input
type="text"
name="date"
placeholder="yyyy年mm月dd"
onkeyup="
var v = this.value;
if (v.match(/^\d{4}$/) !== null) {
this.value = v + '年';
} else if (v.match(/^\d{4}年\d{2}$/) !== null) {
this.value = v + '月';
}"
maxlength="10"
>
Hope this is what you are looking for!
I had some trouble getting the currently accepted answers to work properly while retaining the ability to backspace. This was my solution. It retains backspacing and also doesn't show the slash until the number following it is typed.
const maskDate = value => {
let v = value.replace(/\D/g,'').slice(0, 10);
if (v.length >= 5) {
return `${v.slice(0,2)}/${v.slice(2,4)}/${v.slice(4)}`;
}
else if (v.length >= 3) {
return `${v.slice(0,2)}/${v.slice(2)}`;
}
return v
}
I've also create a github gist for this snippet here.
I have solved this issue a simple function(without regular expressions and only for the format 'dd/mm/yyyy'). And the important thing is that My function pays attention to the maximum values of the date(31) and month(12). For example, You can not input 32/11/2000 or 20/13/2000.
function maskForDate(value) {
if (value.length > 10) {
return value.substring(0, 10);
}
switch (value.length) {
case 1:
if (value > 3) {
value = "3";
}
break;
case 2:
if (value > 31) {
value = "31";
}
break;
case 3:
case 4:
if (value[2] !== "/") {
value = value.substr(0, 2) + "/" + value[2];
}
if (value[3] > 1) {
value = value.substr(0, 3) + "1";
}
break;
case 5:
if (value.substr(3, 2) > 12) {
value = value.substr(0, 3) + "12";
}
break;
case 6:
case 7:
if (value[5] !== "/") {
value = value.substr(0, 5) + "/" + value[5];
}
if (value[6] < 1) {
value = value.substr(0, 6) + "1";
}
break;
default:
break;
}
return value;
}
Try out this code, this will format your date in mm/dd/yyyy format as you type it in the input box.
Create an onchange event on the input box and call the date_formator function with the input date.
function date_formator(date) {
date = date.replace('//', '/');
var result = date.split("/");
var length = result.length;
// Append "/" after the last two charas, if more than 2 charas then remove it
if (length <= 2 && result[length - 1] != "") {
var last_two_digits = result[length -1];
if (last_two_digits.length >= 2) {
date = date.slice(0, -last_two_digits.length);
date = date + last_two_digits.slice(0,2) + "/";
}
}
if (typeof result[2] != "undefined") {
var year = result[2];
if (year.length > 4) {
date = date.slice(0, -year.length);
year = year.slice(0, 4);
date = date + year;
}
}
return date;
}
This works quite well (tried it in console on the jquery mask page)
if (locale !=='' && locale==='zh_CN') {
$('#text12').mask('9999年99月99日');
}
else {
$('#text12').mask('99/99/9999');
}
but if you want the mask format to show up in the input field you need to pass it as placeholder attribute
$('#text12').attr('placeholder', '9999年99月99日')
hope this helps
Related
I'm trying to make a mask react date dd/mm/yyyy to a custom date input.
If i press the keys slow, the mask is setted correct dd/mm/yyyy, but supposing i press the numbers rapid, my mask is breaking
This is my component:
<DateInput
name="date"
placeholder="Data"
value={this.props.data}
dateFormat="DD/MM/YYYY"
onChange={this.props.changeDataTarefa}
animation="none"
onKeyUp={() => this.props.changeDataTarefaMask(this.fixDatePattern(this.props.data))}/>
this is my functions:
fixDatePattern(currDate) {
var currentDate = currDate;
if (currentDate){
var currentLength = currentDate.length;
var lastNumberEntered = currentDate[currentLength - 1];
}
if (!this.isNumber(lastNumberEntered) && currentDate) {
return currentDate.substring(0, currentLength - 1);
}
if (currentLength > 10) {
return currentDate.substring(0, 10);
}
let dateCountTracker = 0
if (currentLength == 1 && currentDate > 1) {
var transformedDate = "0" + currentDate + '/';
dateCountTracker = 2;
currentLength = transformedDate.length;
return transformedDate;
} else if (currentLength == 4 && currentDate[3] > 3) {
let transformedDate = currentDate.substring(0, 3) + "0" + currentDate[3] + '/';
dateCountTracker = 5;
currentLength = transformedDate.length;
return transformedDate;
} else if (currentLength == 2 && (dateCountTracker != 2 && dateCountTracker != 3)) {
dateCountTracker = currentLength;
return currentDate + '/';
} else if (currentLength == 5 && (dateCountTracker != 5 && dateCountTracker != 6)) {
dateCountTracker = currentLength;
return currentDate + '/';
}
dateCountTracker = currentLength;
return currentDate;
}
isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Instead of using keyup, use keypress event on input. And you could also use react input mask plugin for same.
You can use below code for key press event and please check working stackblitz demo.
render() {
return (
<div>
<span>Date : </span>
<input type="text" maxLength="10" placeHolder="dd/mm/yyyy" onKeyPress={this.onKeyPress}/>
</div>
)
}
onKeyPress(e){
let input = e.target;
if(e.charCode < 47 || e.charCode > 57) {
e.preventDefault();
}
var len = input.value.length;
if(len !== 1 || len !== 3) {
if(e.charCode == 47) {
e.preventDefault();
}
}
if(len === 2) {
input.value += '/';
}
if(len === 5) {
input.value += '/';
}
}
You could use below react input mask plugins to achieve requirement.
imaskjs and react-input-mask
I have an input field which has a data manipulation and is a decimal field. Everything works fine except when I put in more than 3 numbers it will lose the current caret and set it to the end of the field because of the field formatting.
Example:
123 works fine
1234 will result in 1’234.00 and the caret is after the last 0. How is it possible to set the caret back to its original position? (Between 4 and the .)
function thousenderSign(number) {
number = '' + number;
if (number.length > 3) {
var mod = number.length % 3;
var output = (mod > 0 ? (number.substring(0, mod)) : '');
for (i = 0; i < Math.floor(number.length / 3); i++) {
if ((mod == 0) && (i == 0)) {
output += number.substring(mod + 3 * i, mod + 3 * i + 3);
} else {
output += "'" + number.substring(mod + 3 * i, mod + 3 * i + 3); // set the sign
}
}
return (output);
} else return number;
}
ko.extenders.numeric = function(target, precision) {
var result = ko.pureComputed({
read: target,
write: function(newValue) {
var current = target();
var roundingMultiplier = Math.pow(10, precision);
var newValueAsNum = null;
if (newValue !== undefined && newValue !== 0 && newValue !== null) {
newValueAsNum = newValue.toString().replace("'", "");
// provide only int fort he function
var onlyInt = newValueAsNum.split(".");
// Remove more then 2 digits after the dot
if (onlyInt.length > 1 && onlyInt[1].length > 2) {
onlyInt[1] = onlyInt[1].toString().substring(0, 2);
}
}
var valueToWrite = (Math.round(newValueAsNum * roundingMultiplier) / roundingMultiplier) === 0 ? null : Math.round(newValueAsNum * roundingMultiplier) / roundingMultiplier;
// thousender sign
if (newValueAsNum !== null && newValueAsNum.length > 3) {
valueToWrite = thousenderSign(onlyInt[0]) + "." + (onlyInt.length > 1 ? onlyInt[1] : '00');
}
if (valueToWrite !== current) {
target(valueToWrite);
} else {
if (newValue !== current) {
target.notifySubscribers(valueToWrite);
}
}
}
}).extend({
notify: 'always'
});
result(target());
return result;
};
function ExampleViewModel() {
self = this;
self.counterofferPremium = ko.observable().extend({
numeric: 2
});
};
var viewModel = new ExampleViewModel();
ko.applyBindings(viewModel);
<!doctype html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
</head>
<body>
<input data-bind="value: counterofferPremium, valueUpdate: 'afterkeydown'" type="text" />
</body>
</html>
The simplest thing to do is get rid of the valueUpdate setting so that the formatting happens after the user is done editing the number.
To have it work interactively, you need to add an input event handler that
Finds how many digits are behind the cursor (this happens before reformatting)
Does a setTimeout to allow the reformatting to happen
Sets the cursor position after the same number of digits
Also note that your formatter gets weird for very long numbers. You might want to replace it with a call to toLocaleString with some additional substitutions.
function thousenderSign(number) {
number = '' + number;
if (number.length > 3) {
var mod = number.length % 3;
var output = (mod > 0 ? (number.substring(0, mod)) : '');
for (i = 0; i < Math.floor(number.length / 3); i++) {
if ((mod == 0) && (i == 0)) {
output += number.substring(mod + 3 * i, mod + 3 * i + 3);
} else {
output += "'" + number.substring(mod + 3 * i, mod + 3 * i + 3); // set the sign
}
}
return (output);
} else return number;
}
ko.extenders.numeric = function(target, precision) {
var result = ko.pureComputed({
read: target,
write: function(newValue) {
var current = target();
var roundingMultiplier = Math.pow(10, precision);
var newValueAsNum = null;
if (newValue !== undefined && newValue !== 0 && newValue !== null) {
newValueAsNum = newValue.toString().replace("'", "");
// provide only int fort he function
var onlyInt = newValueAsNum.split(".");
// Remove more then 2 digits after the dot
if (onlyInt.length > 1 && onlyInt[1].length > 2) {
onlyInt[1] = onlyInt[1].toString().substring(0, 2);
}
}
var valueToWrite = (Math.round(newValueAsNum * roundingMultiplier) / roundingMultiplier) === 0 ? null : Math.round(newValueAsNum * roundingMultiplier) / roundingMultiplier;
// thousender sign
if (newValueAsNum !== null && newValueAsNum.length > 3) {
valueToWrite = thousenderSign(onlyInt[0]) + "." + (onlyInt.length > 1 ? onlyInt[1] : '00');
}
if (valueToWrite !== current) {
target(valueToWrite);
} else {
if (newValue !== current) {
target.notifySubscribers(valueToWrite);
}
}
}
}).extend({
notify: 'always'
});
result(target());
return result;
};
function ExampleViewModel() {
self = this;
self.counterofferPremium = ko.observable().extend({
numeric: 2
});
self.findPlace = function (data, event) {
const pos = event.target.selectionEnd;
var numbersBeforePos = event.target.value.substr(0, pos).replace(/\D/g, '').length;
setTimeout(function() {
const formattedValue = event.target.value;
const numbersNow = event.target.value.replace(/\D/g, '').length;
if (numbersNow >= numbersBeforePos) {
// find the numbersBeforePos-th number
const re = /\d/g;
var newPos;
while (numbersBeforePos--) {
newPos = 1 + re.exec(formattedValue).index;
}
event.target.setSelectionRange(newPos, newPos);
}
}, 0);
};
};
var viewModel = new ExampleViewModel();
ko.applyBindings(viewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<input data-bind="value: counterofferPremium, valueUpdate: 'afterkeydown', event: {input: findPlace}" type="text" />
I have researched all over the place for a phone number validation in JavaScript that adds spacing as they type.
The closest code I came to was
$('#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;
});
http://jsfiddle.net/ssthil/nY2QT/.
Expect that is American Mobile Numbers. Anyone know how to do Australia format (XXXX XXX XXX). I tried moving the digits around in the JavaScript but nothing seemed to work.
Try this code :
while (val.length > 3) {
if(newVal.length > 4){
newVal += val.substr(0, 3) + ' ';
val = val.substr(3);
} else {
newVal += val.substr(0, 4) + ' ';
val = val.substr(4);
}
}
newVal += val;
this.value = newVal;
});
Working fiddle :
http://jsfiddle.net/nY2QT/718/
Modifying your code a little bit you can get something like this:
$('#ssn').on('input', function() {
var val = this.value.replace(/\D/g, '');
if(val.length > 10) {
this.value = this.value.slice(0,12);
} else {
this.value = (val.slice(0,4) + ' ' + val.slice(4,7) + ' ' + val.slice(7,10)).trim();
}
});
I have made some changes with loop hope it will works
$('#ssn').keyup(function() {
var val = this.value.replace(/\D/g, '');
var newVal = '';
var flag = true;
while (val.length > 3) {
if(flag){
flag=false;
newVal += val.substr(0, 4) + '-';
val = val.substr(4);
} else {
newVal += val.substr(0, 3) + '-';
val = val.substr(3);
}
}
newVal += val;
if(this.value.length >= 5){
this.value = newVal;
}
});
You could have instead three <input /> elements, give them each maxlength="4", maxlength="3", and maxlength="3" respectively. And as soon as the user completes each input, they're moved to the following:
HTML
<form>
<input maxlength="4" autofocus="autofocus" name="first"/>
-
<input maxlength="3" name="second"/>
-
<input maxlength="3" name="third"/>
</form>
Javascript/jQuery
// Autofocus second after first is complete
$('[name="first"]').keyup(function() {
if ( $(this).val().length == 4) {
$('[name="second"]').focus();
}
});
// Autofocus third after second is complete
$('[name="second"]').keyup(function() {
if ( $(this).val().length == 3) {
$('[name="third"]').focus();
}
});
// Alert numer after third is complete
$('[name="third"]').keyup(function() {
if ( $(this).val().length == 3) {
alert("Number: " + $('[name="first"]').val() + "-" + $('[name="second"]').val() + "-" + $('[name="third"]').val() + ".");
}
});
Also, to valide for only numbers, you can use RegEx:
// The following code is RegEx, used to validate the inputs so that the user can only type in numbers
$('[name="first"], [name="second"], [name="third"]').on('input', function (event) {
this.value = this.value.replace(/[^0-9]/g, '');
});
// Support for old browsers
$('[name="first"], [name="second"], [name="third"]').on('keyup', function (event) {
this.value = this.value.replace(/[^0-9]/g, '');
});
Eureka!
Edit: answer to Z-Dog's "question":
// Autofocus first if backspace is pressed and this is empty
if (!e) e = window.event;
var keyCode = e.keyCode || e.which;
if (keyCode == '8' && $(this).val().length == 0){
$('[name="first"]').focus();
// And delete last character
$('[name="first"]').val(
function(index, value){
return value.substr(0, value.length - 1);
});
return false;
}
Eureka 2.0!
Use Jquery Mask plug-in
https://igorescobar.github.io/jQuery-Mask-Plugin/
It simple to integrate ans use
Use this code it might work
document.getElementById('ssn').addEventListener('input', function (e) {
e.target.value = e.target.value.replace(/(\d{4}) ?(\d{3}) ?(\d{3})/,
'$1 $2 $3');
});
I have an iput field:
<input type="text" name="time" class="time" value="3" />
I need that value to be like 03:00
More examples of what I need:
1 = 01:00
12 = 12:00
12:2 = 12:20
2:2 = 02:20
02:2 = 02:20
340 = 340:00
340:1 = 340:10
You know the rest. How can I solve this in jquery/javascript?
This is what I try in jQuery:
$('input').blur(timeFormat);
function timeFormat(e){
skjema.find('input.tid').each(function(){
if($(this).val().length != 0){
var tid = $(this).val().toString();
if(tid.length == 1){
$(this).val(String("0" + tid));
}
if(tid.indexOf(':') == -1){
$(this).val(tid.toString() + ':00');
}
}
});
}
This is what I have made now and it does the job, but it is somewhat bulky :)
function timeFormat(e){
skjema.find('input.tid').each(function(){
if($(this).val().length != 0){
var tid = $(this).val().toString();
tid = (tid.length == 1) ? '0' + tid : tid;
tid = (tid.indexOf(':') == -1) ? tid + ':00' : tid;
if(tid.indexOf(':') != -1){
var arr = tid.split(':');
var before = arr[0].toString();
var after = arr[1].toString();
before = (before.length == 0) ? '00' : before;
before = (before.length == 1) ? '0' + before : before;
after = (after.length == 0) ? '00' : after;
after = (after.length == 1) ? after + '0' : after;
console.log('before: ' + before + ' After: ' + after);
tid = before + ':' + after;
}
}
$(this).val(tid);
});
}
You can do this with some simple regex:
function time( str ) {
if ( !/:/.test( str ) ) { str += ':00'; }
return str.replace(/^\d{1}:/, '0$&').replace(/:\d{1}$/, '$&0' );
}
If you want to make sure only the expected format is accepted, add this line at the top of the function:
if ( /[^:\d]/.test( str ) ) { return false; }
Demo: http://jsfiddle.net/elclanrs/MzgMz/
YOu can try something like this using datejs library:-
var dateString = "12";
var date = new Date.parseExact(dateString, "hh:mm");
check this DEMO
$('input').blur(timeFormat);
function timeFormat(e){
$("div").find('input').each(function(){
if($(this).val().length != 0){
var tid = $(this).val().toString();
if(tid.length == 1){
$(this).val(String("0" + tid));
}
if(tid.indexOf(':') == -1){
$(this).val(tid.toString() + ':00');
}
if(tid.indexOf(':') == 2){
$(this).val(tid.toString() + '0');
}
}
});
}
<title>Insert Colon in the Time Format</title>
<script type="text/javascript">
function formatTime(objFormField){
intFieldLength = objFormField.value.length;
if(intFieldLength==2 || intFieldLength == 2){
objFormField.value = objFormField.value + ":";
return false;
}
}
</script>
Enter time <input type="text" maxlength="5" minlength="5" onKeyPress="formatTime(this)"/>
Pseudo:
val ← value from field ($('.time').val())
colonPos ← position of . in val
If colonPos equals -1, result ← padZero(val) + ':00'
Else, result ← padZero(val[:colonPos]) + ':' + padZero(val[colonPos + 1:])
function prettyTime(t){
// will output a time providing leading zeros and minute field
// (doesn't need jQuery)
x=t.split(":");
for (var i=0; i<2; i++)
x[i] = (x[i]) ? Array(3-x[i].length).join('0') + x[i] : '00';
return x.join(":");
}
// --
$('input').blur(timeFormat);
function timeFormat(e){
skjema.find('input.tid').each(function(){
$(this).val(function(i, v) { return prettyTime(v); })
});
}
Maybe u can try this plugin.. Worked for me
Usage Examples:
$("#tbPlain").timefield();
$("#tb12Hour").timefield({ 'hourFormat': '12'});
$("#tb24Hour").timefield({ 'hourFormat': '24'});
$("#tbWithInvalidHandler").timefield({
'hourFormat': '24',
'onError' : function(){
alert(this.value+' is not a valid time!');
this.style.backgroundColor='red';
}
});
$("#tbOnOff").timefield();
$("#btnTurnOff").click(function(){
$("#tbOnOff").timefield('turnOffTimeField');
});
Live Example:
https://jsfiddle.net/sajjansarkar/bst3cw2g/
I have a problem masking a phone input with jQuery and Masked Input Plugin.
There are 2 possible formats:
(XX)XXXX-XXXX
(XX)XXXXX-XXXX
Is there any way to mask it accepting both cases?
EDIT:
I tried:
$("#phone").mask("(99) 9999-9999");
$("#telf1").mask("(99) 9999*-9999");
$("#telf1").mask("(99) 9999?-9999");
But it doesn't works as I would like.
The closest one was (xx)xxxx-xxxxx.
I would like to get (xx)xxxx-xxxx when I type the 10th number, and (xx)xxxxx-xxxx when I type the 11th. Is it posible?
Try this - http://jsfiddle.net/dKRGE/3/
$("#phone").mask("(99) 9999?9-9999");
$("#phone").on("blur", function() {
var last = $(this).val().substr( $(this).val().indexOf("-") + 1 );
if( last.length == 3 ) {
var move = $(this).val().substr( $(this).val().indexOf("-") - 1, 1 );
var lastfour = move + last;
var first = $(this).val().substr( 0, 9 );
$(this).val( first + '-' + lastfour );
}
});
Here is a jQuery phone number mask. No plugin required.
Format can be adjusted to your needs.
Updated JSFiddle.
HTML
<form id="example-form" name="my-form">
<input id="phone-number" name="phone-number" type="text" placeholder="(XXX) XXX-XXXX">
</form>
JavaScript
$('#phone-number', '#example-form')
.keydown(function (e) {
var key = e.which || e.charCode || e.keyCode || 0;
$phone = $(this);
// Don't let them remove the starting '('
if ($phone.val().length === 1 && (key === 8 || key === 46)) {
$phone.val('(');
return false;
}
// Reset if they highlight and type over first char.
else if ($phone.val().charAt(0) !== '(') {
$phone.val('('+$phone.val());
}
// 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('');
}
});
Actually the correct answer is on http://jsfiddle.net/HDakN/
Zoltan answer will allow user entry "(99) 9999" and then leave the field incomplete
$("#phone").mask("(99) 9999-9999?9");
$("#phone").on("blur", function() {
var last = $(this).val().substr( $(this).val().indexOf("-") + 1 );
if( last.length == 5 ) {
var move = $(this).val().substr( $(this).val().indexOf("-") + 1, 1 );
var lastfour = last.substr(1,4);
var first = $(this).val().substr( 0, 9 );
$(this).val( first + move + '-' + lastfour );
}
});
You need a jQuery plugin for the mask works as well.
-- HTML --
<input type="text" id="phone" placeholder="(99) 9999-9999">
<input type="text" id="telf1" placeholder="(99) 9999*-9999">
<input type="text" id="telf2" placeholder="(99) 9999?-9999">
-- JAVASCRIPT --
<script src="https://raw.githubusercontent.com/igorescobar/jQuery-Mask-Plugin/master/src/jquery.mask.js"></script>
<script>
$(document).ready(function($){
$("#phone").mask("(99) 9999-9999");
$("#telf1").mask("(99) 9999*-9999");
$("#telf2").mask("(99) 9999?-9999");
});
</script>
You can use the phone alias with Inputmask v3
$('#phone').inputmask({ alias: "phone", "clearIncomplete": true });
$(function() {
$('input[type="tel"]').inputmask({ alias: "phone", "clearIncomplete": true });
});
<label for="phone">Phone</label>
<input name="phone" type="tel">
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask#3.3.7/dist/inputmask/inputmask.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask#3.3.7/dist/inputmask/inputmask.extensions.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask#3.3.7/dist/inputmask/inputmask.numeric.extensions.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask#3.3.7/dist/inputmask/inputmask.date.extensions.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask#3.3.7/dist/inputmask/inputmask.phone.extensions.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask#3.3.7/dist/inputmask/jquery.inputmask.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask#3.3.7/dist/inputmask/phone-codes/phone.js"></script>
https://github.com/RobinHerbots/Inputmask#aliases
Using jQuery Mask Plugin there is two possible ways to implement it:
1- Following Anatel's recomendations:
https://gist.github.com/3724610/5003f97804ea1e62a3182e21c3b0d3ae3b657dd9
2- Or without following Anatel's recomendations:
https://gist.github.com/igorescobar/5327820
All examples above was coded using jQuery Mask Plugin and it can be downloaded at:
http://igorescobar.github.io/jQuery-Mask-Plugin/
var $phone = $("#input_id");
var maskOptions = {onKeyPress: function(phone) {
var masks = ['(00) 0000-0000', '(00) 00000-0000'];
mask = phone.match(/^\([0-9]{2}\) 9/g)
? masks[1]
: masks[0];
$phone.mask(mask, this);
}};
$phone.mask('(00) 0000-0000', maskOptions);
With jquery.mask.js
http://jsfiddle.net/brynner/f9kd0aes/
HTML
<input type="text" class="phone" maxlength="15" value="85999998888">
<input type="text" class="phone" maxlength="15" value="8533334444">
JS
// Function
function phoneMask(e){
var s=e.val();
var s=s.replace(/[_\W]+/g,'');
var n=s.length;
if(n<11){var m='(00) 0000-00000';}else{var m='(00) 00000-00000';}
$(e).mask(m);
}
// Type
$('body').on('keyup','.phone',function(){
phoneMask($(this));
});
// On load
$('.phone').keyup();
Only jQuery
http://jsfiddle.net/brynner/6vbrqe6z/
HTML
<p class="phone">85999998888</p>
<p class="phone">8599998888</p>
jQuery
$('.phone').text(function(i, text) {
var n = (text.length)-6;
if(n==4){var p=n;}else{var p=5;}
var regex = new RegExp('(\\d{2})(\\d{'+p+'})(\\d{4})');
var text = text.replace(regex, "($1) $2-$3");
return text;
});
The best way to do this is using the change event like this:
$("#phone")
.mask("(99) 9999?9-9999")
.on("change", function() {
var last = $(this).val().substr( $(this).val().indexOf("-") + 1 );
if( last.length == 3 ) {
var move = $(this).val().substr( $(this).val().indexOf("-") - 1, 1 );
var lastfour = move + last;
var first = $(this).val().substr( 0, 9 ); // Change 9 to 8 if you prefer mask without space: (99)9999?9-9999
$(this).val( first + '-' + lastfour );
}
})
.change(); // Trigger the event change to adjust the mask when the value comes setted. Useful on edit forms.
The best way to do it on blur is:
function formatPhone(obj) {
if (obj.value != "")
{
var numbers = obj.value.replace(/\D/g, ''),
char = {0:'(',3:') ',6:' - '};
obj.value = '';
upto = numbers.length;
if(numbers.length < 10)
{
upto = numbers.length;
}
else
{
upto = 10;
}
for (var i = 0; i < upto; i++) {
obj.value += (char[i]||'') + numbers[i];
}
}
}
As alternative
function FormatPhone(tt,e){
//console.log(e.which);
var t = $(tt);
var v1 = t.val();
var k = e.which;
if(k!=8 && v1.length===18){
e.preventDefault();
}
var q = String.fromCharCode((96 <= k && k <= 105)? k-48 : k);
if (((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) && e.keyCode!=46 && e.keyCode!=37 && e.keyCode!=8 && e.keyCode!=39) {
e.preventDefault();
}
else{
setTimeout(function(){
var v = t.val();
var l = v.length;
//console.log(l);
if(k!=8){
if(l<4){
t.val('+7 ');
}
else if(l===4){
if(isNaN(q)){
t.val('+7 (');
}
else{
t.val('+7 ('+q);
}
}
else if(l===7){
t.val(v+')');
}
else if(l===9){
t.val(v1+' '+q);
}
else if(l===13||l===16){
t.val(v1+'-'+q);
}
else if(l>18){
v=v.substr(0,18);
t.val(v);
}
}
else{
if(l<4){
t.val('+7 ');
}
}
},100);
}
}
I was developed simple and easy masks on input field to US phone format jquery-input-mask-phone-number
Simple Add jquery-input-mask-phone-number plugin in to your HTML file and call usPhoneFormat method.
$(document).ready(function () {
$('#yourphone').usPhoneFormat({
format: '(xxx) xxx-xxxx',
});
});
Working JSFiddle Link https://jsfiddle.net/1kbat1nb/
NPM Reference URL https://www.npmjs.com/package/jquery-input-mask-phone-number
GitHub Reference URL https://github.com/rajaramtt/jquery-input-mask-phone-number
If you don't want to show your mask as placeholder you should use jQuery Mask Plugin.
The cleanest way:
var options = {
onKeyPress: function(phone, e, field, options) {
var masks = ['(00) 0000-00000', '(00) 00000-0000'];
var mask = (phone.length>14) ? masks[1] : masks[0];
$('.phone-input').mask(mask, options);
}
};
$('.phone-input').mask('(00) 0000-00000', options);
Yes use this
$("#phone").inputmask({"mask": "(99) 9999 - 9999"});
Link here
$('.phone').focus(function(e) {
// add mask
$('.phone')
.mask("(99) 99999999?9")
.focusin(function(event)
{
$(this).unmask();
$(this).mask("(99) 99999999?9");
})
.focusout(function(event)
{
var phone, element;
element = $(this);
phone = element.val().replace(/\D/g, '');
element.unmask();
if (phone.length > 10) {
element.mask("(99) 99999-999?9");
} else {
element.mask("(99) 9999-9999?9");
}
}
);
});