4.表单提交(空格提交的问题)
例 4.1(form.submitIEFF.html)
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<script language=javascript>
function check()
{
var form = document.getElementById("regForm");
if (form.user.value == "")
{
alert("用户名不能为空!");
}
else
{
form.submit();
}
}
</script>
<form method=post id="regForm" action="jsp1.jsp">
用户<input type="text" name="user"/><br>
<INPUT TYPE="button" onclick="check();" id="regBut" value="提交"/>
</form>
马克-to-win:以上例子很好,但有个问题,当光标放在文本框里时,即使空格,回车也会提交。不信你试试,浏览器(IE和火狐)都这样。下面给出解决办法。
例 4.1_a
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<script language=javascript>
function check()
{
var form = document.getElementById("regForm");
if (form.user.value == "")
{
alert("用户名不能为空!");
}
else
{
form.submit();
}
}
</script>
<form method=post id="regForm" action="jsp1.jsp">
用户<input type="text" name="user" onkeydown="if(event.keyCode==13) return false;"/><br>
<INPUT TYPE="button" onclick="check();" id="regBut" value="提交"/>
</form>
或者用下面的例子,里面用了onSubmit,只要提交,它就会被执行。
例 4.2(onSubmitReturnIEFF.html)
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<script language=javascript>
function check(form)
{
/*onSubmit (Event handler)
The user has clicked on the submit button in a form.
Property/method value type: Boolean primitive
JavaScript syntax: - myObject.onsubmit = aHandler
HTML syntax: <FORM onSubmit="..."> <HTMLTag onSubmit="...">
As the <FORM> submit button is clicked, this event is triggered.If you return the value true, the event will be passed to the browser for further processing and the form will be submitted.
Returning false inhibits this action and discards the message;
the form will not be submitted. This provides a means of
inhibiting <FORM> submits when the form data is bad.
*/
if (form.user.value == "")
{
alert("用户名不能为空!");
return false;
}
return true;
}
</script>
更多请见:https://blog.youkuaiyun.com/qq_43650923/article/details/102160310
博客主要围绕JavaScript表单提交时的空格提交问题展开。给出了表单提交的示例代码,指出当光标在文本框时,空格、回车都会提交表单的问题,并提供了解决办法,如在文本框添加onkeydown事件,还介绍了使用onSubmit事件处理表单提交的方式。
507

被折叠的 条评论
为什么被折叠?



