Brittany Brittany - 3 months ago 40
Javascript Question

Redirect After Form Submit

I have a form set up and a javascript file (as shown below) that I want to validate the input and then redirect to a different website (index.html). The validation works perfectly, but I can't figure out how to get the form to redirect to the wanted page instead of just showing the post return. The form posts to a php file (which I am unable to access), and I would like the return of that file to then be displayed on index.html.

Form:

<form name="form" action="register.php" onsubmit="return validateInput()" method="POST" >
<fieldset>
<legend>Personal Details</legend>
<label>Name</label><br>
<input type="text" name="name"><br><br>
<label>Email</label><br>
<input type="text" name="email"><br><br>
<label>Date of Birth</label><br>
<input type="text" name="dob"><br>
</fieldset>
<input type="submit" name="submit"> <input type="reset" name="reset">
</form>


JavaScript File:

function validateInput() {

var check = document.forms["form"].elements;

for (var i = 0; i < check.length; i++) {
var test = check[i];

if (test.type === "text" && test.value === "") {
displayMsg("Please fill out all fields" +test.innerHTML);
return false;
}
if (test.type === "date") {
var pattern = /^\d{1,2}\/\d{1,2}\/\d{4}$/;

if (!test.value.match(pattern)) {
displayMsg("Please enter a valid date of birth");
return false;
}
}
else if (test.name === "email") {
var re = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;

if (!test.value.match(re)) {
displayMsg("Please enter a valid email address");
return false;
}
}
}
return true;
}

function displayMsg(msg) {
var ele = document.getElementById("msg");
ele.className = "show";
ele.innerHTML = "<p>" + msg + "</p>";
}

window.onload = function() {
var check = document.forms["form"].elements;
for (var i = 0; i < check.length; i++) {
check[i].addEventListener('click', function() {
var ele = document.getElementById("msg");

if(ele.className != "hide") {
ele.className = "hide";
}
});
}
}

Answer

Instead of return true; you can set the location that you want using window.location.href and use return false; to prevent the default submission of the form:

function validateInput() {
    ....
    window.location.href = 'index.html';
    return false;
}