Home > Mobile >  Why does form submit with preventDefault?
Why does form submit with preventDefault?

Time:08-27

I'm trying to loop over all the fields in this form. I've collected all the form fields in an array and I have a forEach to loop over them, but I'm stuck on the preventDefault() not working.

const form = document.getElementById("fakeForm");

Array.from(form.elements).forEach((element, e) => {
  e.preventDefault();
  if (element == "") {
    alert("Please complete all fields!");
  }
});
<form action="" name="fakeForm" id="fakeForm">
  <input type="text" placeholder="first name">
  <input type="text" placeholder="last name">
  <input type="submit" value="submit">
</form>

CodePudding user response:

preventDefault is a property of event. You are trying to call it on an index of an array called e in this example.

Usually you wait for submit event and then call preventDefault:

document.querySelector('form').addEventListener('submit', e => {
  e.preventDefault()
})

Edit:

If you want to check if every field is valid, you should use validation.

But if you don't want to do this for some reason...

const form = document.querySelector('form')
form.addEventListener('submit', e => {  
  const isFormFilled = Array.from(form.elements).every((element) => {
    return element !== ''
  });

  if (!isFormFilled) {
    e.preventDefault()
  }
})
  • Related