2

Есть скрипт маски телефона, у которого пара не совсем приятных моментов. Первый - это возможность удалить семерку. И второй - когда номер уже полностью набран, то при вводе уже лишней цифры, она вводится и тут же удаляется.

window.addEventListener("DOMContentLoaded", function() {
function setCursorPosition(pos, elem) {
    elem.focus();
    if (elem.setSelectionRange) elem.setSelectionRange(pos, pos);
    else if (elem.createTextRange) {
        var range = elem.createTextRange();
        range.collapse(true);
        range.moveEnd("character", pos);
        range.moveStart("character", pos);
        range.select()
    }
}

var is_del = false; var is_back = false; function mask(event) { var curent_position = -1; if(event.type == "keyup"){ curent_position = this.selectionStart; } var matrix = "+7 (___) ___ ____", i = 0, def = matrix.replace(/\D/g, ""), val = this.value.replace(/\D/g, ""); if (def.length >= val.length) val = def; this.value = matrix.replace(/./g, function(a) { return /[_\d]/.test(a) && i <= val.length ? val.charAt(i++) : i < val.length ? a : i++ == 6 && val.length == 4 && event.keyCode !=8 && event.keyCode !='' ? ")" : "" }); is_back = is_del = false; if(event.keyCode == 8) is_back = true; else if(event.keyCode == 46) is_del = true; if (event.type == "blur") { if (this.value.length == 2) this.value = ""; } else if(curent_position != -1){ if(is_del || is_back){ setCursorPosition(curent_position, this); } } else if(event.type == "focus") setCursorPosition(this.value.length, this); }; var input = document.querySelector("#tel"); input.addEventListener("focus", mask, false); input.addEventListener("blur", mask, false); input.addEventListener("keyup", mask, false); });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="tel">
Kromster
  • 13,809
Sevastopol'
  • 28,195
  • Так, стоп.. Я где-то это уже видел... – Qwertiy Oct 10 '17 at 09:48
  • Хватит велосипеды плодить, это очень плохо. Особенно в таких мелочах. Уже куча готовых решений. Например писали выше, или это http://js.nicdn.de/bootstrap/formhelpers/docs/phone.html – Geri4 Oct 12 '17 at 06:15

2 Answers2

4

Есть библиотека https://github.com/igorescobar/jQuery-Mask-Plugin, которая предоставляет маски для ввода. Добавляем свой хак, чтобы +7 нельзя было удалить и решение готово.

window.addEventListener("DOMContentLoaded", function() {
  $('#tel').mask('+7 (000) 000 0000');
  $('#tel').on('keypress, keydown', function(event) {
    var $field = $(this);
    var readOnlyLength = 2;
if ((event.which != 37 &amp;&amp; (event.which != 39)) &amp;&amp;
  ((this.selectionStart &lt; readOnlyLength) ||
    ((this.selectionStart == readOnlyLength) &amp;&amp; (event.which == 8)))) {
  return false;
}

}); });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.12/jquery.mask.js"></script>

<input type="text" id="tel" value="+7">
Komdosh
  • 12,128
3

Вот так уже должно работать так как вы хотите.

window.addEventListener("DOMContentLoaded", function() {
    function setCursorPosition(pos, elem) {
        elem.focus();
        if (elem.setSelectionRange)
            elem.setSelectionRange(pos, pos);
        else if (elem.createTextRange) {
            var range = elem.createTextRange();
            range.collapse(true);
            range.moveEnd("character", pos);
            range.moveStart("character", pos);
            range.select()
        }
    }
var is_del = false;
var is_back = false;
var def_position = -1;
function mask(event) {
    var curent_position = -1;
    if (event.type == "keyup") {
        curent_position = this.selectionStart;
    }
    var matrix = "+7 (___) ___ ____",
            i = 0,
            def = matrix.replace(/\D/g, ""),
            val = this.value.replace(/\D/g, "");
    if (def.length &gt;= val.length)
        val = def;
    if (event.type == "input") {
        if(this.value.charAt(0) !='+'){
          this.value = this.value.replace(/^(.{1})./, '$1+');
        }
        if(this.value.charAt(1) != '7'){
          this.value = this.value.replace(/^(.{2})./, '$17');
        }
        if (this.value.length &lt; 2) {
            this.value = matrix.replace(/./g, function(a) {
                return /[_\d]/.test(a) &amp;&amp; i &lt;= val.length ? val.charAt(i++) : i &lt; val.length ? a : i++ == 6 &amp;&amp; val.length == 4 &amp;&amp; event.keyCode != 8 &amp;&amp; event.keyCode != '' ? ")" : ""
            });
        }
    }
    else {
        this.value = matrix.replace(/./g, function(a) {
            return /[_\d]/.test(a) &amp;&amp; i &lt;= val.length ? val.charAt(i++) : i &lt; val.length ? a : i++ == 6 &amp;&amp; val.length == 4 &amp;&amp; event.keyCode != 8 &amp;&amp; event.keyCode != '' ? ")" : ""
        });
    }
    is_back = is_del = false;
    if (event.keyCode == 8)
        is_back = true;
    else if (event.keyCode == 46)
        is_del = true;
    if (event.type == "blur") {
        if (this.value.length == 2)
            this.value = "";
    } else if (curent_position != -1) {
        if (is_del || is_back) {
            setCursorPosition(curent_position, this);
        }
    } else if (event.type != "input")
        setCursorPosition(this.value.length, this);
}
;
var input = document.querySelector("#tel");
input.addEventListener("focus", mask, false);
input.addEventListener("blur", mask, false);
input.addEventListener("keyup", mask, false);
input.addEventListener("input", mask, false);

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" maxlength="17" id="tel">
Raz Galstyan
  • 8,258