不能为我的生活弄清楚这一点。任何帮助将不胜感激!
这是我在测试脚本时在 Google Chrome 中收到的消息:
导航到http://localhost/contact.php form2.js:2 Uncaught ReferenceError: form is not definedform2.js:2 validatecontact.php:24 onsubmit 导航到http://localhost/contact.php
我的contact.php文件:
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="form2.js"></script>
<?php require 'Includes/Header.php'; ?>
<div class="wrapper">
<div id="contact-form">
<h5>Contact Form</h5>
<form name="contact" form method="post" action="contact.php"
onsubmit="return validate(contact)">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<label for="email">Email:</label>
<input type="email" id="email" name="email">
<label for="message">Message:</label>
<textarea id="message" name="message"></textarea>
<button type="submit">Submit</button>
</form>
<div class="clear"></div>
</div>
</div>
<?php require 'Includes/Footer.php'; ?>
Run Code Online (Sandbox Code Playgroud)
我的 form2.js 文件:
function validate(contact){
var name = form.name.value;
var email = form.email.value;
var message = form.message.value;
if (name.length == 0 || name.length > 200)
{alert ("You must enter a name.");
return false;
}
if (email.length == 0 || email.length > 200)
{alert ("You must enter a email.");
return false;
}
if (message.length == 0)
{alert ("You must enter a message.");
return false;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
小智 6
表单是一个 javascript 对象。该对象不存在于该文件中,这就是抛出错误的原因。如果您想验证此表单,您需要首先使用 document.contact 从 DOM 获取对它的引用。
function validate(contact){
var form = document.contact,
name = form.name.value,
email = form.email.value,
message = form.message.value;
if (name.length == 0 || name.length > 200) {
alert ("You must enter a name.");
return false;
}
if (email.length == 0 || email.length > 200) {
alert ("You must enter a email.");
return false;
}
if (message.length == 0) {
alert ("You must enter a message.");
return false;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)