How do would you go about redirecting to different page when a user correctly fills a form? I have tried two different methods: location.href = "otherpage.html";
and location.replace("otherpage.html")
however they aren’t working.
Adding window.
in front isn’t changing anything either.
<!DOCTYPE html>
<head>
<script src="javascript/srcipt.js"></script>
</head>
<html>
<form name="form" onsubmit="Distance();" method="POST">
<p>
<label for="dLondon">Distance from London</label>
<input type="number" id="dLondon" name="dLondon" min="0" required>
<label for="dLondon">miles</label>
</p>
<p>
<label for="dCanberra">Distance from Canberra</label>
<input type="number" id="dCanberra" name="dCanberra" min="0" required>
<label for="dCanberra">miles</label>
</p>
<p>
<label for="dOttawa">Distance from Ottawa</label>
<input type="number" id="dOttawa" name="dOttawa" min="0" required>
<label for="dOttawa">miles</label>
</p>
<input type="submit" value="Submit">
</form>
</html>
function Distance() {
let dLondon = document.forms["form"]["dLondon"].value;
let dOttawa = document.forms["form"]["dOttawa"].value;
let dCanberra = document.forms["form"]["dCanberra"].value;
if ((3900 <= dLondon) && ( dLondon <= 5200)) {
if ((5500 <= dCanberra) && (dCanberra <= 6700)) {
if ((6700 <= dOttawa) && (dOttawa <= 9300)) {
location.href = "otherpage.html";
}
else {
alert("Ottawa Distance isn't correct !");
}
}
else {
alert("Canberra distance isn't correct !");
}
}
else {
alert("London Distance isn't correct ! ");
}
}
2
Answers
I've found the solution, I just had to change
onsbumit="Distance()";
toobsubmit="return Distance();
in html and addreturn false;
at the end of theDistance()
function.Instead of "hijacking" the submit event for validating the form input, use the
invalid
event. You can use the attributesmin
andmax
(among others) to decide if the value is valid. The form will only submit if the form is valid, and you can use the standardaction
attribute on the form to specify the URL.