我有一个简单的HTML表单,只有一个字段。格式如下-
<table>
<form action="insert.php" method="post" name="discover" onSubmit="return discover()">
<tr><td></td><td><input type="text" name="name"></td></tr>
<tr><td></td><td><br><br><p class="submit"><input type="submit" id="submit" name="commit" value="Register"></p><br><br><br></td></tr>
</form>
</table>
验证js文件是-
function discover() {
var stu_name=document.forms["discover"]["name"].value;
if (stu_name==null || stu_name=="" || stu_name.length<7) {
alert("Please provide Your full name");
return false;
}
}
我已经包含验证js文件正确。但这种验证不起作用。
try this
<script type="text/javascript">
function check()
{
var stu_name=document.forms["discover"]["stu_name"].value;
if (stu_name==null || stu_name=="" || stu_name.length<7)
{
alert("Please provide Your full name");
return false;
}
}
</script>
<form action="" method="post" name="discover" id="discover" onsubmit="return check();">
<input type="text" name="stu_name" id="stu_name" value="" />
<input type="submit" id="sub" />
</form>
在你的js文件中,
测试:function discover()
{
var stu_name=document.forms["discover"]["name"].value;
if (stu_name==null || stu_name=="" || stu_name.length<7)
{
alert("Please provide Your full name");
return false;
}
}
这个作品
function discover()
{
var stu_name=document.getElementsByName("name");
if (stu_name==null || stu_name=="" || stu_name.length<7)
{
alert("Please provide Your full name");
return false;
}
}
您正在混合表单名称和函数名称,并且输入需要缺少的id。而且你忘了关闭函数。试试这个
<script type="text/javascript">
function _discover()
{
var stu_name=document.forms["discover"]["stu_name"].value;
if (stu_name==null || stu_name=="" || stu_name.length<7)
{
alert("Please provide Your full name");
return false;
}
}
</script>
<table>
<form action="" method="post" name="discover" onSubmit="return _discover();">
<tr><td></td><td><input type="text" name="name" id="stu_name"> </td></tr>
<tr><td></td><td><br><br><p class="submit"><input type="submit" id="submit" name="commit" value="Register"></p><br><br><br></td></tr>
</form>
</table>
您的代码中除了函数名与表单同名之外没有任何问题
查看这个链接,这里是工作代码
jsbin
function disc() {
var stu_name=document.forms["discover"]["name"].value;
if (stu_name==null || stu_name=="" || stu_name.length<7) {
alert("Please provide Your full name");
return false;
}
}
<table>
<form action="insert.php" method="post" name="discover" onSubmit="return disc()">
<tr><td></td><td><input type="text" name="name"></td></tr>
<tr><td></td><td><br><br><p class="submit"><input type="submit" id="submit" name="commit" value="Register"></p><br><br><br></td></tr>
</form>
</table>