-1

I want to make validation for my input text form, that user cannot go further unless all input forms will be completed. i want to make it through every input that even if first is completed, user needs to complete another 2 etc. but at this moment i am only able to make it through the first one and have no idea how to iterate it through every input text.

My html:

<div class="write-to-us">
                <div class="col-md-12 field">
                    <p>Write to us</p>
                </div>
                <div class="col-md-12 field">
                    <div class="my-form">
                        <label>Name</label>
                        <input  type="text" name="subject" class="my-text-input">
                        <div class="label-error">Write your Name</div>
                    </div> 
                </div>
                <div class="col-md-12 field">
                    <div class="my-form">
                        <label>Surname</label>
                        <input type="text" name="subject" class="my-text-input">
                        <div class="label-error">Write your surname</div>
                </div>
                </div>
                <div class="col-md-12 field">
                    <div class="my-form">
                        <label">Question</label>
                        <textarea type="text" name="subject" class="my-text-input"></textarea>
                    </div>
                </div>
                <div>
                    <button class="my-button">Check it</button>
                </div>
            </div>

And my js code for iteration:

myFunction: function() {
            var $formField = $('.write-to-us');
            if (!$formField.exists()) {
                return;
            }
            initValidation();
            function initValidation() {
                var errorMsg = $formField.find('.label-error');
                var button = $formField.find('.my-button');
                var input = $formField.find('input');
                var inputContainer = $formField.find('.my-form')
                button.click(function(event) {
                    if(!input.val().trim()) {
                        errorMsg.css('visibility', 'visible');
                        inputContainer.addClass('error');
                        event.preventDefault();
                    }
                });
        },

I guess that problem is with .find and should be some jQuery .each but i have no idea how to change it.

Gladi
  • 137
  • 2
  • 13

1 Answers1

0

I would try doing something like this rather than find.

function initValidation() {
  $('.my-button').click(function(){
    $("input").each(function() {
      var element = $(this);
      if (element.val() == "") {
        element.closest('.label-error').css('visibility', 'visible');
        element.closest('.my-form').addClass('error');
      }
    });
  });
}
Arbin Shrestha
  • 155
  • 1
  • 7