这是我的代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type = "text/javascript">
function validate(){
var warnings = "some warnings";
document.getElementById("alert").innerHTML = warnings;
document.getElementById("alert").styledisplay = "block";
return true;
}
</script>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
</head>
<body>
<div id = "alert"></div>
<div id = wrapper>
<h2>Enter Your Info</h2>
<form name = "myForm" onSubmit = "javascript:validate()">
<div>
<label for = "username">User Name:</label>
<input type = "text" name = "username" id = "username"/>
</div>
<div>
<label for = "firstname">First Name:</label>
<input type = "text" name = "firstname" id = "firstname"/>
</div>
<div>
<label for = "lastname">Last Name:</label>
<input type = "text" name = "lastname" id = "lastname"/>
</div>
<div>
<label for = "password">Password:</label>
<input type = "password" name = "password" id = "password"/>
</div>
<div>
<input type = "submit" value = "submit" id = "submit"/>
</div>
</form>
</div>
</body>
</html>
我遇到的问题是当我点击提交按钮时没有任何反应。不知道为什么,我是 java 脚本和 html 的新手,但我读过的所有内容都说这应该有效任何帮助将不胜感激。
最佳答案
你总是返回 true
。所以表单将提交。而是试试这个:
<form name="myForm" onSubmit="return validate()">
和
function validate() {
var warnings = validate();
document.getElementById("alert").innerHTML = warnings;
document.getElementById("alert").styledisplay = "block";
if(warnings) return false; //If any warning i don't want to submit.
return true;
}
补充一下。 if(warnings)
将根据您设置的警告的初始状态使条件失败,或者从您的验证函数中不设置任何内容(如果验证成功)返回空字符串或返回 null、undefined 等或什么都不返回...
关于javascript - onSubmit 事件没有任何反应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18926889/