【问题标题】:form validation not alerting after checking conditions检查条件后表单验证不提醒
【发布时间】:2014-10-23 21:14:10
【问题描述】:

我正在尝试使用 javascript 验证 HTML 表单,但由于没有弹出警报,我认为我的 checkSubmit() 函数没有被调用。但是,在函数开头添加一个额外的警报后,它确实会触发,但在检查第一个条件后不会弹出更多警报。

<script language="javascript" type="text/javascript">
  function checkSubmit() {

     alert("Hello from Javascript!");
     if (document.getElementById("user").value.toString.length <1) {
        alert("Please enter a user name.");
        return false;
     }

     if (document.getElementById("location").value.toString.length <1) {
        alert("Please enter a location.");
        return false;
     }
     if (document.getElementById("depart").value.toString.length <1) {
        alert("Please enter a department.");
        return false;
     }
     if (document.getElementById("category").value.toString.length <1) {
        alert("Please enter a problem type.");
        return false;
     }
     if (document.getElementById("info").value.toString.length <1) {
        alert("Please enter a problem description.");
        return false;
     }
     alert("Hello from Javascript2!");
     return true;
   }   
</script>

<form name="submit" type="submit" method="POST" onsubmit="return checkSubmit();">

   [...]

   <input type="submit" name="submit" value="Submit" >
</form>

除非我犯了一个错误(我相信事后看来会很明显),是否应该弹出第二个警报,无论任何条件是真还是假?

【问题讨论】:

  • 控制台报错了吗?也许找不到您的控件之一...
  • 我猜你遇到了一个错误,比如未定义值。
  • 啊哈。我的第一个输入框中缺少“id=”标签。但是,现在我遇到了相反的问题 - 即使 ID 为“user”的框中包含文本,我也会收到输入用户名的警报。

标签: javascript html forms validation


【解决方案1】:

您不需要toString,因为.value 已经是一个字符串,而且无论如何您都在错误地使用它——您需要说.toString()。事实上,它返回函数定义,所以.length 将是0。而且正如您所说,您需要正确设置每个框的id 属性。

function checkSubmit() {

    if (document.getElementById("user").value.length < 1) {
        alert("Please enter a user name.");
        return false;
     }

     if (document.getElementById("location").value.length < 1) {
        alert("Please enter a location.");
        return false;
     }

     if (document.getElementById("depart").value.length < 1) {
        alert("Please enter a department.");
        return false;
     }

     if (document.getElementById("category").value.length < 1) {
        alert("Please enter a problem type.");
        return false;
     }

     if (document.getElementById("info").value.length < 1) {
        alert("Please enter a problem description.");
        return false;
     }

     return true;
}

【讨论】:

  • 谢谢。这现在有效。希望这个问题可以帮助那些陷入死胡同认为他们的“onsubmit”不起作用的其他人,因为该页面最初似乎是在没有任何其他操作的情况下提交/刷新。
猜你喜欢
  • 2012-06-29
  • 2013-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多