There are 2 pieces of code: the first is responsible for checking the fields, the second sends the form.

I can't insert the dispatch code after checking the fields. How to do it? In JS is not strong, I really ask for help.

Check:

$("#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; }); 

Form submission code:

 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 answer 1

    For example:

     $("#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; } });