3

I'm very inexperienced with programming so sorry if this is stupid question.

I'm creating a form which the user will be able to submit using a button. I have used script functions to decide whether they will return true or false, with the only condition being that the input boxes must be filled. Here is a simplified version of my JavaScript and HTML code, I've only included one of the input boxes. (My real code has six)

function validateEmail() {
    var x = document.forms["myForm"]["email"].value;
    if (x == null || x == "") {
        alert("Email must be filled out");
        return false;
	}
	else {
		return true;
	}
}
<form name="myForm" 
onsubmit="validateEmail()" method="post" action="Different_Page.html">
  
<label for="email">Email Address:</label>
<input type="email" name="email">
  
<input type="submit" value="Submit">
</form>

The issue is that if the user does not type in their email and the function returns false, it still goes to the page I only want it to go to when it returns true. So in other words, I want it to do nothing and stay on this page, but ONLY when the script returns false. How do I accomplish this?

1 Answer 1

4

You have to return false from the onsubmit function and not just from a function that that function calls.

onsubmit="return validateEmail()"

That said, modern code would avoid intrinsic event attributes in favour of binding event handlers with JavaScript …

function validateEmail(evt) {
  var x = this.elements.email.value;
  if (x == "") {
    alert("Email must be filled out");
    evt.preventDefault();
  }
}

document.getElementById('myForm').addEventListener("submit", validateEmail);
<form id="myForm" method="post" action="Different_Page.html">

  <label for="email">Email Address:</label>
  <input type="email" name="email">

  <input type="submit" value="Submit">
</form>


… or forget JavaScript entirely and just use the validation features introduced in HTML 5.

<form method="post" action="Different_Page.html">

  <label for="email">Email Address:</label>
  <input type="email" name="email" required>

  <input type="submit" value="Submit">
</form>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks very much, that last HTML solution is very simple. I didn't even need to use JavaScript after all.

Your Answer

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.