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>
3 Answers 3
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;
}
1 Comment
return false, you need to use event.preventDefault() to stop the form submission.When making a condition on an if statement the "is equal to" comparison symbol is == or ===. = is used for assigning variables.
Comments
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.
Comments
Explore related questions
See similar questions with these tags.