I have this html code where the index.html loads first. It has a text field and a submit button. When the submit button is clicked, it calls the validateForm() function. Suppose the text field is empty, it should alert that it is empty, if it isn't then a new html page would load (either in new tab or current one) which is supposed to be welcome.html
So my problem is, the welcome.html file isn't loading. I even changed the "welcome.html" in window.location.href = "welcome.html"
to "https://www.google.com" . The page still wouldn't load. What's wrong and what am I missing here ?
Any help is appreciated.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form</title>
<script src="/validateForm.js"></script>
</head>
<body>
<form method="get" onsubmit="return validateForm()">
Name: <input type="text" name="name" id="name">
<input type="submit" value="Submit">
</form>
</body>
</html>
validateForm.js
function validateForm() {
var name = document.getElementById("name");
var nameData = name.value;
if (nameData == "" || nameData == null) {
alert("Name must be filled!");
}
else {
window.location.href = "welcome.html";
}
}
welcome.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome :)</title>
</head>
<body>
<h1>Welcome!</h1>
</body>
</html>
CodePudding user response:
Use action
attribute
You can use the action
attribute on the form to forward to a URL on success:
<form method="get" action="welcome.html" onsubmit="return validateForm()">
Name: <input type="text" name="name" id="name">
<input type="submit" value="Submit">
</form>
return value of validateForm()
See this?
onsubmit="return validateForm()"
Your validateForm
doesn't return anything.
It is convention that return false
means "stop processing the form" and a true-ish value means continue
, which in turn means the action
attribute mentioned above leads to welcome.html
as you wanted.
The modified function could be this:
function validateForm() {
var name = document.getElementById("name");
var nameData = name.value;
if (nameData == "" || nameData == null) {
alert("Name must be filled!");
return false;
}
return true;
}