0

I have a javascript function that is called on submit.

<script>
function validateLogin() {
 var x = document.forms["login"]["username"].value;
 var y = document.forms["login"]["password"].value;
 if (x == "" && y == "") {
 alert("Please enter an email and password!");
 } else if (x == "") {
 alert("Please enter an email!");
 } else if (y == "") {
 alert("Please enter a password!");
 } else {
 return false;
 }
}
</script>

And is called like so onsubmit="return validateLogin()"

The function works fine however when the alert appears and you click okay, the page refreshes. Is there a way too stop it refreshing?

Tushar
87.4k21 gold badges164 silver badges182 bronze badges
asked Jul 17, 2015 at 9:41

2 Answers 2

1
  1. You need to return false; to stop form submission and page redirection, when error occurs.
  2. No need of last else
  3. trim username value

Code:

<script>
function validateLogin() {
 var x = document.forms["login"]["username"].value.trim();
 var y = document.forms["login"]["password"].value;
 if (x == "" && y == "") {
 alert("Please enter an email and password!");
 return false; // Here
 } else if (x == "") {
 alert("Please enter an email!");
 return false; // Here
 } else if (y == "") {
 alert("Please enter a password!");
 return false; // Here
 }
}
</script>

I'll also suggest you to use HTML-5 required attribute for required fields.

<form name="login">
 Username: <input type="text" name="username" required />
 Password: <input type="password" name="password" required />
</form>
answered Jul 17, 2015 at 9:42
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for the advice on html5 and the required attribute. In combination with the html5 constraint validation api the topic starter should be able to solve his problem more accurate.
0
function validateLogin() {
 var x = document.forms["login"]["username"].value;
 var y = document.forms["login"]["password"].value;
 if (x == "" && y == "") {
 alert("Please enter an email and password!");
return false;
 } else if (x == "") {
 alert("Please enter an email!");
 return false;
 } else if (y == "") {
 alert("Please enter a password!");
 return false;
 }
}
answered Jul 17, 2015 at 9:49

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.