Как вставить дефис "-" после 4 цифр автоматически в TextBox в html5? - PullRequest
2 голосов
/ 02 ноября 2019

Я сделал проверку в поле ввода в html5, чтобы получить этот формат 03xx-xxxxxxx.

pattern="03\d{2}-\d{7}"

Теперь я хочу добавить этот символ дефиса автоматически после четвертой цифры. Как это сделать?

Ответы [ 2 ]

1 голос
/ 03 ноября 2019

Я сделал проверку в поле ввода в html5, чтобы получить этот формат 03xx-xxxxxxx.

Один альтернативный подход (без JavaScript) - использовать три поля <input />.

Рабочий пример:

#country,
#region {
width: 16px;
}

#local {
width: 56px;
}
<input type="text" id="country" value="03" readonly />
<input type="text" id="region" pattern="[0-9]{2}" placeholder="88" />
-
<input type="text" id="local" pattern="[0-9]{7}" placeholder="8888888"/>
1 голос
/ 02 ноября 2019

Я должен посоветовать вам против этого типа редактирования ввода, так как это обычно расстраивает, когда вам нужно редактировать опечатки.

Также я не имею представления о проблемах, связанных с доступностью.

Шаблон ввода проверяет только данные при отправке, поэтому это не то, что вы ищете.

Тем не менее, вот одно из возможных решений в JS:

// select the input element
var i = document.querySelector('input.hyphen');
// number of charatcers before the hyphen
var n = 4;
// run this function everytime the user release a key
i.addEventListener('keyup', function (event) { 
  // text cleared of all dashes
  var t = i.value.replace(/-/g, '');
  // save the carret position
  var s = i.selectionStart;
  // beguining string with n digits
  var b = t.substr(0, n);
  // end string with what's left (maxLength)
  var e = t.substr(n);
  // if there are more then n digits
  if (e.length) {
    // join then with a dash
    i.value = [b, e].join('-');
    // if the caret was before the dash put it back to the saved position
    if (s <= n) i.setSelectionRange(s, s);
    // if the caret was next to the dash put it after
    if (s == n+1) i.setSelectionRange(s+1, s+1);
  // if there's no end string then no need for dashes, just show the beguining
  } else i.value = b;
});
<input class="hyphen" placeholder="0000-0000000" maxlength="12">
...