0

Сделал логику фокуса для инпут полей код рабочий, но согласитесь, плохо когда код дублируется:

/* Для фокуса инпутов после ввода цифр в смс авторизации */
$('.input').on('keyup', function() {
  if (!this.value.match(/[^0-9]/g)) {
    this.value = this.value.slice(0, 6);
    if ($(this).val().length === 6) {
      $(this).next('.confirm').focus();
    }
  } else {
    this.value = ''
  }
});

$('.field').on('keyup', function() { if (!this.value.match(/[^0-9]/g)) { this.value = this.value.slice(0, 1); if ($(this).val().length === 1) { $(this).next().focus().select(); $(this).next('.confirm').focus(); } } else { this.value = '' } });

.field {width: 25px;}
hr {border-color: red;margin:32px 0;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="auth-wait__fields">
  <input type="text" class="field" placeholder="_">
  <input type="text" class="field" placeholder="_">
  <input type="text" class="field" placeholder="_">
  <input type="text" class="field" placeholder="_">
  <input type="text" class="field" placeholder="_">
  <input type="text" class="field" placeholder="_">

  <button type="button" class="confirm">Подтвердить</button>
</div>

<hr>

<div class="auth-wait__fields">
  <input type="text" class="input" placeholder="_">

  <button type="button" class="confirm">Подтвердить</button>
</div>

Вынес её в функцию, но получаю ошибки:

"Uncaught TypeError: Cannot read properties of undefined (reading 'match')"

// Для фокуса инпутов после ввода цифр в смс авторизации
function authFocus(sliceNum, oldMultiInput) {
  if (!this.value.match(/[^0-9]/g)) {
    this.value = this.value.slice(0, sliceNum);
    if ($(this).val().length === sliceNum) {
      if (oldMultiInput) {
        $(this).next().focus().select();
      }
      $(this).next('.auth-wait__send').focus();
    }
  } else {
    this.value = ''
  }
}

$('.input').on('keyup', function() { authFocus(6, false) });

//Второй вариант вариант

$('.field').on('keyup', function() { authFocus(1, false) });

.field {width: 25px;}
hr {border-color: red;margin:32px 0;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="auth-wait__fields">
  <input type="text" class="field" placeholder="_">
  <input type="text" class="field" placeholder="_">
  <input type="text" class="field" placeholder="_">
  <input type="text" class="field" placeholder="_">
  <input type="text" class="field" placeholder="_">
  <input type="text" class="field" placeholder="_">

  <button type="button" class="confirm">Подтвердить</button>
</div>

<hr>

<div class="auth-wait__fields">
  <input type="text" class="input" placeholder="_">

  <button type="button" class="confirm">Подтвердить</button>
</div>
Aleksandr
  • 840

1 Answers1

0

Вы вызывает функцию, в которой нет элемента, this получить нельзя. Но Вы можете передать в эту функцию Ваш элемент и сразу с ним работать, примеры ниже:

function Example_one(){
  /* this здесь не доступен */
  console.log(this.innerHtml); // ошибка
}

Example_one();

function Example_two (el){ /* обращаюсь к объетку используя не this, а el */ console.log(el.innerHtml); } Example_two(this); // Передаю свой объект используя ключевое слово this

Примерно вот так это работает

artemgh
  • 659
  • 5
  • 20