0

Upon clicking submit, the function doesn't seem to get called and the form submits even if the return is false.

 function validateForm() {
 if (document.getElementById("nm").value="") {
 alert("You must enter a name!"); 
 return false;
 }
 if (document.getElementById("em").value="") {
 alert("email required"); 
 return false;
 }
 return true;
 }

And the HTML:

 <form onsubmit=" return validateForm();" action="myscript.php" id="primary">
 <label>Name<input type="text" id="nm"></input></label>
 <label>Email<input type="text" id="em"></input></label>
 <input type="submit" id="send" value="submit"></input>
 </form>
Ania Warzecha
1,81614 silver badges26 bronze badges
asked Apr 19, 2014 at 17:06

3 Answers 3

1

You should use the == or === (exact equal to) to compare values, the = operator is used to assign values.

 function validateForm() {
 if (document.getElementById("nm").value == "") {
 alert("You must enter a name!"); 
 return false; 
 }
 if (document.getElementById("em").value == "") {
 alert("email required"); 
 return false; 
 }
 return true;
 }
answered Apr 19, 2014 at 17:08
Sign up to request clarification or add additional context in comments.

1 Comment

Instead of return false, you need to use event.preventDefault() to stop the form submission.
0

When making a condition on an if statement the "is equal to" comparison symbol is == or ===. = is used for assigning variables.

answered Apr 19, 2014 at 17:09

Comments

0

There's already an answer for that here -> onsubmit method doesn't stop submit

Basically you need to use event.preventDefault() to stop the form submission.

answered Apr 19, 2014 at 18:07

Comments

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.