Summary:

I want to create a self-written form that checks the correctness of the user input, that is, whether the user filled the field or not, in the case of a single empty field, the user input highlighted with a red frame

Task: There is a certain condition in the source that checks with arrInput[i].value.length == 0 , but the problem is that when I click the send button, the class specified by arrInput[i].classList.add("form__item"); at the moment disappears . I had to stop the script via alert ();

Source:

 let name = document.querySelector('form input[name=name]'); let lastName = document.querySelector('form input[name=lastName]'); let age = document.querySelector('form input[name=age]'); let send = document.querySelector('form input[type=submit]'); let arrInput = [name, lastName, age]; send.addEventListener('click', checkOut); function checkOut() { for (let i=0 ;arrInput.length > i; i++ ){ if (arrInput[i].value.length == 0){ arrInput[i].classList.add("form__item"); alert(1); } } } 
 .form .form__item.input[type=text] { border: 1px solid red; } 
 <form class="form" action=""> <input type="text" name="name"><br> <input type="text" name="lastName"><br> <input type="text" name="age"><br> <input type="submit" value="send"> </form> 

  • He does not disappear. At you at a page the page is overloaded anew. You need to stop submitting the form if there are errors. - Stepan Kasyanenko
  • Is event.preventDefault () ?? - John
  • Yes, there was a problem in it! Thank you for not giving an answer, but just giving a hint. - John

1 answer 1

It should be added to the condition event.preventDefault()

 send.addEventListener('click', checkOut); function checkOut() { for (let i=0 ;arrInput.length > i; i++ ){ if (arrInput[i].value.length == 0){ arrInput[i].classList.add("form__item"); event.preventDefault(); } } } 
  • There is no need to preventDefault at every iteration of the loop, it’s enough to call once before or after. - Grundy
  • And it is better not to use the 'click' event on the button, but to use the submit event on the form. - Stepan Kasyanenko