我写了这段代码(发布到PHP页面),这样如果客人没有输入他们的名字,就会弹出一个警告框。但是,即使我在名称文本框中放了一些东西并提交它,警告框仍会弹出,它会将$ _POST ['gname']提交给服务器。
这是JavaScript:
<script type="text/javascript">
function gSubmit()
{
if (document.getElementById("gname").value.length === 0)
{
alert("For completing the form, it requires you to input a Name");
return false;
}
else
{
document.getElementById("guestbook").innerHTML=("<p><b><center>Thank you for submitting the Guestbook");
window.location = "guestbook.php";
return true;
}
}
</script>
这是HTML:
<form id="guestbook" name="guestbook" method="post" action="guestbook.php">
<center>
<table border="0px">
<tr>
<td>
<p align="right">Name :</p></td><td> <input type="text" name="gname" id="gname" />
</td>
</tr>
<tr>
<td>
<p align="right">E-mail :</p></td><td><input type="text" name="gemail" />
</td>
</tr>
<tr>
<td>
<p align="right">Telephone No :</p>
</td>
<td>
<input type="text" name="gtpn" />
</td>
</tr>
<tr>
<td>
<p align="right">Product Order / Comment / Messages :</p>
</td>
<td>
<textarea name="gtxtfld" id="gtxtfld" cols="32"></textarea>
</td>
</tr>
</table>
<br /><br />
<input type="submit" value="submit" name="submit" onclick="gSubmit();" />
<input type="reset" value="reset" name="reset" />
</form>
答案 0 :(得分:2)
将您的gSubmit()
功能更改为:
if (document.getElementById("gname").value === "")
{
alert("For completing the form, it requires you to input a Name");
return false;
}
else
{
document.getElementById("guestbook").innerHTML=("<p><b><center>Thank you for submitting the Guestbook");
return true;
}
在您的HTML中,将onclick="gsubmit()"
更改为onclick="return gsubmit()"
。
请注意,不会显示else子句中的消息,因为那时表单已提交。
此外,您必须比较value
gname
字段,而不是innerHTML
字段。它必须与空字符串(“”)进行比较,而不是空格(“”)。
答案 1 :(得分:1)
要检查文本框中是否包含值,您可以使用以下内容:
if (document.getElementById("gname").value.length > 0)
{
alert("For completing the form, it requires you to input a Name");
//by returning false, you stop the submission from happening
return false;
}
else
{
document.getElementById("guestbook").innerHTML=("<p><b><center>Thank you for submitting the Guestbook");
return true; //allow the submission to go through
}
在你的onclick事件中:
onclick="return gSubmit();"