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
2 Answers 2
- You need to
return false;to stop form submission and page redirection, when error occurs. - No need of last
else trimusername 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
Tushar
87.4k21 gold badges164 silver badges182 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Marcel
+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.
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
Yatin Khullar
1,5901 gold badge13 silver badges27 bronze badges
Comments
lang-js