У меня есть вход для телефона, Введенные номера ограничены 10
и отформатированы в (xxx) xxx-xxxx
.
Он отлично работает на рабочем столе, так как только цифры c кнопки справа и сверху клавиатура.
Но на мобильных устройствах, когда я нажимаю на ввод для ввода чисел, в некоторых браузерах клавиатура не отображается, а для других браузеров, если отображается клавиатура, пользователь может ввести любое количество чисел, и цифры Не отформатирован так (xxx) xxx-xxxx
.
Вы можете найти форму здесь http://mdev.epizy.com/phone/phone.html
Вот скрипка: https://jsfiddle.net/54mupvz9/
html:
<input type="text" id="phone">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
Javascript / jQuery:
(function ($) {
$.fn.usPhoneFormat = function (options) {
var params = $.extend({
format: 'xxx-xxx-xxxx',
international: false,
}, options);
if (params.format === '(xxx) xxx-xxxx') {
$(this).on('keydown touchend', function (e) {
//If user clicks a button that is not (Backspace, End, Home, Left, Right)
if(8 != e.which && 35 != e.which && 36 != e.which && 37 != e.which && 39 != e.which){
//If the button is not a numeric button from right and top of keyboard
if (!(( 48 <= e.which && e.which <= 57) || ( 96 <= e.which && e.which <= 105 ))) {
return false;
}
}
var curchr = this.value.length;
var curval = $(this).val();
//If count of numbers = 3 and the button is not 'Backspace', Surround the numbers with (), So the value becomes (xxx)
if (curchr == 3 && e.which != 8 && e.which != 0) {
$(this).val('(' + curval + ')' + " ");
}
//Else if count = 9 add '-', So the value becomes (xxx) xxx-
else if (curchr == 9 && e.which != 8 && e.which != 0) {
$(this).val(curval + "-");
}
//Set max length of input to 14, So the value is (xxx) xxx-xxxx
$(this).attr('maxlength', '14');
});
$(this).bind('paste', function (e) {
e.preventDefault();
var inputValue = e.originalEvent.clipboardData.getData('Text');
if (!$.isNumeric(inputValue)) {
return false;
} else {
inputValue = String(inputValue.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3"));
$(this).val(inputValue);
$(this).val('');
inputValue = inputValue.substring(0, 14);
$(this).val(inputValue);
}
});
}
}
}(jQuery));
//Apply formatting to the input
$('#phone').usPhoneFormat({
format: '(xxx) xxx-xxxx',
});