The site has two forms, the script processes the two forms as one. How to fix? so that the script processes them separately.

var field = new Array("name", "phone"); //поля обязательные $("form").submit(function() { // обрабатываем отправку формы var error = 0; // индекс ошибки $("form").find(":input").each(function() { // проверяем каждое поле в форме for (var i = 0; i < field.length; i++) { // если поле присутствует в списке обязательных if ($(this).attr("name") == field[i]) { //проверяем поле формы на пустоту if (!$(this).val()) { // если в поле пустое $(this).css('border', 'red 2px solid'); // устанавливаем рамку красного цвета error = 1; // определяем индекс ошибки } else { $(this).css('border', 'green 2px solid'); // устанавливаем рамку обычного цвета } } } }) //провека номера телефона var phone = $("#phone").val(); if (!isValidPhone(phone)) { error = 2; $("#phone").css('border', 'red 2px solid'); // устанавливаем рамку красного цвета } if (error == 0) { // если ошибок нет то отправляем данные return true; } else { return false; //если в форме встретились ошибки , не позволяем отослать данные на сервер. } function isValidPhone(phone) { var pattern = new RegExp(/^((8|\+7)[\- ]?)?(\(?\d{3}\)?[\- ]?)?[\d\- ]{7,10}$/); return pattern.test(phone); } }) 

    3 answers 3

    Write

     $(this).find(":input").each(function() { // проверяем каждое поле в форме 

    instead

     $("form").find(":input").each(function() { // проверяем каждое поле в форме 

    and

     $(this).find(".phone")... 

    instead

     $("#phone")... 

    accordingly changing id="phone" to class="phone" .

    • Everything turned out Thank you!) - Ramzes
    1. Function

        function isValidPhone (phone) 
      need to move beyond the bounding range
        $ ("form"). submit (function () ... 
      Otherwise, it turns out that every time you try to submit a form, your function is recreated.

    2. Do not create items with duplicate IDs on one page. Use your unique ID for each item. But for your task it is better, as indicated above, to use classes.

    3. Vyacheslav Potseluyko correctly showed you an example: choose all the forms and cycle you hang up on each of your events sending the form. Then the binding will be more targeted.

    4. if (error == 0) { return true; } else { return false; }

    There is a little extra. The form and so will be sent, if you do not return false force. So just enough

    if (error !== 0) return false;

    But returning false is not the most correct option in this case. It is better to terminate the execution of the event using the event.stopPropagation () method or event.preventDefault () (see examples on how to do this).

    • Thank you for the amendment!) - Ramzes

    On pure JS it will look like this.

     var forms = document.querySelectorAll("form"); for (var i = 0; i < forms.length; i++) { forms[i].onsubmit = function() { // код } } 
    • Correct the markup of someone good :( - Vyacheslav Potseluyko