我有一个 php每个页面都包含页眉和页脚的网站。在我的一个页面上,我有一个名为 “orderForm” 的表单,onSubmit 等于 “return(validate())”。在我的 header (包含在该页面上)中,我有一个名为 function validate() 的函数。
我的问题是试图从我的头文件中验证订单。我知道当我的验证函数包含以下内容时它部分起作用:
alert("Test");
return false;
当我提交表单时收到提醒。
但是当我尝试类似的东西时:
if (document.orderForm.postcode.value.length < 1) {
alert("Postcode field cannot be empty.");
return false;
}
它不验证它,尽管 orderForm 和 postcode 是表单字段的正确名称。这是因为我在将表单放在不同的文件中时包含了头文件吗?
干杯
最佳答案
如果您想按名称进行测试,您可以这样做,假设页面中没有其他加载代码。要点是等待分配验证,直到页面上存在表单。
window.onload=function() {
document.orderForm.onsubmit=function() {
if (this.postcode.value.length < 1) {
alert("Postcode field cannot be empty.");
return false; //cancel submission
}
return true; // allow submission
}
}
要在我的代码中使用 preventDefault,您可以尝试
window.onload=function() {
document.orderForm.onsubmit=function(e) {
var event=e?e:window.event;
if (this.postcode.value.length < 1) {
alert("Postcode field cannot be empty.");
event.preventDefault();
}
}
}
关于javascript - 使用单独 header 中的 JavaScript 验证表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32535433/