0

After validating my form with javascript I can not get it to submit to the server

myForm.addEventListener("submit", validation);
 function validation(e) {
 let data = {};
 e.preventDefault();
 errors.forEach(function(item) {
 item.classList.add("cart__hide");
 });

at the end of the validation I have the following code

 if (!error) {
 myForm.submit();
 }

I also tried

 if (error = false) {
 myForm.submit();
 }
 if ((error == false)) {
 myForm.submit();
 }

when I console log error I am getting all false so the form should submit. I am getting the following console log error

TypeError: myForm.submit is not a function

I did this same validation on an html page and it worked fine. Now I am trying to get it to work on a PHP page and it will not submit. I am not sure why the myForm.submit() is causing the error. Thanks Jon

Saniya syed qureshi
3,1973 gold badges18 silver badges23 bronze badges
asked Oct 16, 2019 at 6:53
2
  • can you share the html side of things. Is myForm definitely set to the right variable? e.g <form id="myForm"></form> and then let myForm = document.getElementById('myForm'); Sounds simple but could be a copy paste error I guess but you've changed IDs Commented Oct 16, 2019 at 6:56
  • Ankur Mishra gave me the solution but thanks much for your willingness to help out a javascript rookie Commented Oct 17, 2019 at 3:52

2 Answers 2

2

Remove e.preventDefault(); from your code and put it in your validation function like this:

if (error) {
 e.preventDefault(); 
}
answered Oct 16, 2019 at 6:57
Sign up to request clarification or add additional context in comments.

Comments

2

What you need to do is to only call Event#preventDefault when there is an error.

myForm.addEventListener("submit", validation);
function validation(e) {
 var error = !form.checkValidity(); // replace this with the actual validation
 if (error) e.preventDefault();
}
<form>
 <input type="text">
 <input type="submit" value="submit">
</form>

answered Oct 16, 2019 at 7:02

1 Comment

@Jon I'm glad I could help. If the answer, solved your problem you can accept it by clicking the check to left of it.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.