Search code examples
javascriptjqueryformsclassjquery-selectors

Form validation in ajax requires only the first input in the class to be filled


I'm trying to do validation for my form. I want to make it so if any item with class "required" is empty the form won't be submitted. Right now this is the case only for the first item in the class. For example, I have 3 inputs with class "required" - name, surname, address. The form is sent when I fill in only name, but surname and address are still empty.

Similar problem with $('.required').addClass('error'); - it should have a red border only in the empty field, but it has it on all the fields with "required" class. Is there a way to fix it?

$(function() {

  $('#form').on('submit', function(e) {

    e.preventDefault();

    if ($('.required').val() === '') {
      $('#add').addClass('error');
      $('.required').addClass('error');
      $('#text').html("Fill in the form.");;
    } else {
      $.ajax({
        type: "post",
        url: 'php/php.php',
        data: new FormData(this),
        processData: false,
        contentType: false,
        success: function() {
          document.getElementById("text").innerHTML = "success";
          document.getElementById("add").style.border = "2px solid green";
        },
        error: function() {
          document.getElementById("text").innerHTML = "error";
          document.getElementById("add").style.border = "2px solid red";
        }
      });
    }

  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<p id="text">Placeholder</p>

<form id="form" method="POST" action="php/php.php">

  <input type="text" name="Name" id="name" class="required"><br>
  <ol>
    <li>
      <input type="number" name="x1" class="required">
      <input type="text" name="xa1" class="required">
      <be>
    </li>
    <li>
      <input type="number" name="x2">
      <input type="text" name="xa2"><br>
    </li>

    <input type="submit" name="Add" id="add">

</form>


Solution

  • $('.required') return a collection of jQuery DOM element, so you need to loop through this collection. Try this solution

        $(function () {
    
            $('#form').on('submit', function (e) {
    
                e.preventDefault();
                let alllfine = true;
                $('.required').each(function () {
                    if ($(this).val() == '') {
                        $('#text').html("Fill in the form.");
                        $('#add').addClass('error');
                        $(this).addClass('error');
                        $(this).css('border', '1px solid red');
                        alllfine = false;
                    } else {
                        $(this).css('border', '1px solid black');
                    }
                })
                if (alllfine) {
                    $.ajax({
                        type: "post",
                        url: 'php/php.php',
                        data: new FormData(this),
                        processData: false,
                        contentType: false,
                        success: function () {
                            document.getElementById("text").innerHTML = "success";
                            document.getElementById("add").style.border = "2px solid green";
                        },
                        error: function () {
                            document.getElementById("text").innerHTML = "error";
                            document.getElementById("add").style.border = "2px solid red";
                        }
                    });
                }
    
            });
    
        });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <p id="text">Placeholder</p>
    
    <form id="form" method="POST" action="php/php.php">
    
        <input type="text" name="Name" id="name" class="required"><br>
        <ol>
            <li>
                <input type="number" name="x1" class="required">
                <input type="text" name="xa1" class="required">
                <be>
            </li>
            <li>
                <input type="number" name="x2">
                <input type="text" name="xa2"><br>
            </li>
    
            <input type="submit" name="Add" id="add">
    
    </form>