提交按钮的onclick事件的JavaScript函数没有验证文本框


JavaScript function on onclick event of submit button not validating textbox

我编写了这段代码(它发布到一个PHP页面),这样如果客人没有输入他们的名字,它就会弹出一个警告框。然而,即使我在name文本框中输入了一些内容并提交了它,警告框仍然会弹出,它会向服务器提交$_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>

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子句中的消息将不会显示,因为到那时表单已经提交了。

另外,您必须比较gname字段的value,而不是innerHTML。它必须与空字符串(")进行比较,而不是与空格(")进行比较。

要检查文本框中是否有值,可以使用如下命令:

 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();"