2

我查看了许多与我的查询类似的帖子,但总的来说,它们对我没有帮助。我认为我的部分问题是我对 JavaScript 太陌生,以至于以前的很多帖子对我来说都太复杂了。我有下面的简单代码,但它似乎不起作用。我没有收到警报,即使函数应该返回“true”,我也不认为表单正在提交。我检查了错误控制台,没有错误。有人可以帮忙吗?

JavaScript:

function submit()
{

var age = document.Message.Age.value;

if (age > 39)
{
    alert("You're old.");
    return false;
}

else
{
    alert("You're young!");
    return true;
}

} 

HTML:

<FORM id = "Message" name = "Message" method = "post" action = "http://cnn.com" onsubmit = "return submit();">

First Name: <INPUT type = "text" name = "Fname"/><br>
Age: <INPUT type = "text" name = "Age"/><br>
<INPUT type="button" name = "Submit" value = "Submit">


</FORM>
4

2 回答 2

1

将您的 HTML 更改为

<FORM id = "Message" name = "Message" method = "post" action = "http://cnn.com" onsubmit = "return submit();">

First Name: <INPUT type = "text" name = "Fname"/><br>
Age: <INPUT type = "text" name = "Age"/><br>
<INPUT type="submit" name = "Submit" value = "Submit">


</FORM>

请注意,输入类型已更改为“提交”,以便实际进行提交。

于 2012-10-20T19:11:06.660 回答
-1

我怀疑您的javascript函数本身是否被调用。如果没有,我认为您需要将您从标签onsubmit移至标签。作为<body><form>

 <body onsubmit"return submit();">

也可以将您的按钮更改为任一类型submit或在下面添加一个onClick()事件:

 <INPUT type="submit" name = "Submit" value = "Submit"/>

或者

 <INPUT type="button" name = "Submit" value = "Submit" onClick="submit()"/>

以下是完整的工作代码(在 chrome 和 IE8 中)示例:

<Html>
 <head>
   <script language="javascript">
   function submit(){
     var age = document.Message.Age.value;
     if (age > 39){
        alert("You're old.");
        return false;
     }else{
        alert("You're young!");
        return true;
     }
   } 
   </script>
  </head>
  <body>
  <FORM id = "Message" name = "Message" method = "post" 
               action = "http://cnn.com" onSubmit = "javascript:return submit();">
    First Name: <INPUT type = "text" name = "Fname"/><br>
    Age: <INPUT type = "text" name = "Age"/><br>
    <INPUT type="submit" name = "Submit" value = "Submit"/>
   </FORM>
  </body>
</html>
于 2012-10-20T19:15:10.493 回答