0

Есть 2 куска кода: первый отвечает за проверку полей, второй отправляет форму.

Не получается вставить код отправки после проверки полей. Как это сделать? В JS не силен, очень прошу помощи.

Проверка:

$("#feedback-form").submit(function(e) {

  var ref = $(this).find("[required]");

  $(ref).each(function() {
    if ($(this).val() == '') {
      alert("Required field should not be blank.");

      $(this).focus();

      e.preventDefault();
      return false;
    }
  });
  return true;
});

Код отправки формы:

document.getElementById('feedback-form').addEventListener('submit', function(evt) {
  var http = new XMLHttpRequest(),
    f = this;
  evt.preventDefault();
  http.open("POST", "http://ravtest1.site88.net/pro-stroy/contacts.php", true);
  http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

  function cheсk_str(str) {
    if ('.txt-required'.length > 0) {
      return true;
    } else {
      $('.msg-form').html("Мало букв");
    }
  }

  http.send("nameFF=" + f.nameFF.value + "&phone=" + f.phone.value + "&contactFF=" + f.contactFF.value + "&messageFF=" + f.messageFF.value);
  http.onreadystatechange = function() {
    if (http.readyState == 4 && http.status == 200) {
      $('.msg-form').html("Спасибо за обращение! Мы свяжемся с Вами в ближайшее время.");
      f.messageFF.removeAttribute('value'); // очистить поле сообщения (две строки)
      f.messageFF.value = '';
    }
  }
  http.onerror = function() {
    $('.msg-form').html("Извините, данные не были переданы");
  }
}, false);

HTML:

<div class="msg-form"></div>
<form method="POST" id="feedback-form">
  <div class="box-input">
    <label for="name">Введите имя</label>
    <input type="text" name="nameFF" id="name">
  </div>
  <div class="box-input">
    <label for="email">Введите e-mail</label>
    <input required="true" type="email" name="contactFF" id="email">
  </div>
  <div class="box-input">
    <label for="phone">Введите контактный телефон</label>
    <input type="tel" name="phone" id="phone">
  </div>
  <div class="box-input">
    <label for="vopr">Задайте вопрос</label>
    <input required="true" type="text" name="messageFF" id="vopr">
  </div>
  <div class="box-button">
    <button type="submit">Отправить</button>
  </div>
</form>

1 ответ 1

0

Например, так:

$("#feedback-form").submit(function(e) {
  var ref = $(this).find("[required]")
                   .filter(function (){ return $(this).val() == '' });

  if (ref.length > 0){
    alert("Required field should not be blank.");
    ref[0].focus();

    // return false в обработчике через jquery автоматически подразумевает 
    //  вызов .preventDefault(): http://stackoverflow.com/a/1357151/4267982
    return false;
  }
});

Ваш ответ

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

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