0

Форма HTML

<div class="payment-form-card">
      <label for="name">Номер карты</label>
      <input type="text" placeholder="XXXX XXXX XXXX XXXX" class="input input-card">
      <div class="cards">
        <div class="cards-visa"></div>
        <div class="card-mastercard"></div>
        <div class="card-mir"></div>
      </div>
      <label for="name">Владелец карты</label>
      <input type="text" placeholder="SURNAME NAME" class="input input-name">
      <label for="name">MM/YY</label>
      <input type="text" placeholder="MM/YY" class="input input-time">
      <label for="name">CVV2/CVC2</label>
      <input type="text" placeholder="XXX" class="input input-code">
      <button class="payment-form-card__pay button_card">Оплатить</button>
    </div>

JS

window.onload = () => {
  let pay_card = document.querySelector('.method-pay__cards'),
    pay_phone = document.querySelector('.method-pay__phone');
  pay_card.addEventListener('click', function () {
    pay_phone.classList.remove('active');
    this.classList.add('active');
  });
  pay_phone.addEventListener('click', function () {
    pay_card.classList.remove('active');
    this.classList.add('active');
  });

  /*Маска*/
  new Cleave('.input-card', {
    creditCard: true
  });
  new Cleave('.input-time', {
    date: true,
    datePattern: ['m', 'y']
  });
  new Cleave('.input-code', {
    blocks: ['3'],
    numericOnly: true
  })
  /*Валидация*/
  var
    number_card = document.querySelector('.input-card'),
  name_card = document.querySelector('.input-name'),
  button_pay_card = document.querySelector('.button_card');

  /*Номер карты*/
  number_card.addEventListener('blur', valid_number_card);
  number_card.addEventListener('focus', focus_element);
  /*Имя карты*/
  name_card.addEventListener('keypress', valid_name_card);
  name_card.addEventListener('blur', reg_name_card);
  name_card.addEventListener('focus', focus_element);

  /*При нажатий на кнопку оплатить*/
  document.querySelector('.button_card').addEventListener('click', function () {
    let inputs_card = document.querySelectorAll('.input');
    for (i = 0; i < inputs_card.length; i++) {
      if (inputs_card[i].value.length == 0) {
        inputs_card[i].classList.add('invalid');
      }
      inputs_card[i].addEventListener('focus', focus_element);
      inputs_card[i].addEventListener('blur', function() {
        if (this.value.length == 0) {
          this.classList.add('invalid');
        } else {
          this.classList.remove('invalid');
        }
      });

    }
  });

  function valid_number_card() {
    if (this.value.length != 0 && this.value.length < 19) {
      this.classList.add('invalid');
    } else {
      this.classList.remove('invalid');
    }
  }

  function valid_name_card() {
    let theEvent = event || window.event,
      key = theEvent.keyCode || theEvent.which;
    key = String.fromCharCode(key);
    let regex = /[a-zа-яА-ЯA-Z\s]/;
    if (!regex.test(key)) {
      theEvent.returnValue = false;
      if (theEvent.preventDefault) theEvent.preventDefault();
    }
  }

  function reg_name_card() {
    let reg = /^[A-Za-zА-Яа-я]+\s[A-Za-zА-Яа-я]+$/gi;
    str = this.value;
    if (this.value != '') {
      if (!reg.test(str)) {
        this.classList.add('invalid');
      } else {
        this.classList.remove('invalid');
      }
    }
  }

  function focus_element() {
    this.classList.remove('invalid');
  }
}

Если на кнопку не нажимать, то функций глобальные работают, но после нажатия работает только то, что находить внутри

document.querySelector('.button_card').addEventListener('click', function () {...});

Помогите решить мою проблему Если быть конкретней, то игнорируются blur и focus, которые указаны за пределами функций нажатия кнопки

4
  • Что есть "функций глобальные"?
    – user176262
    22 апр 2020 в 17:33
  • Не понятно, что у вас там в "глобальных функциях"... но первое, что бросается в глаза: for (i = 0; — она может задеть что-то снаружи... → for( let i = 0 22 апр 2020 в 17:34
  • если добавить функций внутрь, то работают. Странно
    – Лукас
    22 апр 2020 в 17:52
  • без минимальный воспроизводимый пример можно только гадать.
    – Grundy
    22 апр 2020 в 17:59

2 ответа 2

0

Все дело в этом

inputs_card[i].addEventListener('blur', function() {
        if (this.value.length == 0) {
          this.classList.add('invalid');
        } else {
          this.classList.remove('invalid');
        }
      });

Решение

inputs_card[i].addEventListener('blur', function() {
        if (this.value.length == 0) {
          this.classList.add('invalid');
      });

Она мешала выполнению вот этой функций

 number_card.addEventListener('blur', valid_number_card);
 name_card.addEventListener('blur', reg_name_card);
-1

Проблема именно в переменной LET. Это локальная переменная, область видимости которой ограничена. Попробуйте заменить её на VAR - это должно решить вашу проблему

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.