我有一个表单设置和一个javascript文件(如下所示),我想验证输入,然后重定向到另一个网站(index.html)。验证工作完美,但我无法弄清楚如何让表单重定向到想要的页面,而不是只显示返回。表单发布到php文件(我无法访问),我希望返回该文件然后显示在index.html上。
表格:
<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文件:
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";
}
});
}
}
答案 0 :(得分:2)
您可以使用return true;
设置所需的位置,而不是window.location.href
,并使用return false;
来阻止默认提交表单:
function validateInput() {
....
window.location.href = 'index.html';
return false;
}