我查看了一些与我的查询类似的帖子,但总的来说,他们并没有帮助我。我认为我的一部分问题是我对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>
答案 0 :(得分: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>
请注意,输入类型已更改为“提交”,因此实际提交了提交。
答案 1 :(得分:-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>