javascript当中表单提交(空格提交的问题)
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" οnclick="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" οnkeydοwn="if(event.keyCode==13) return false;"/><br>
<INPUT TYPE="button" οnclick="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.csdn.net/qq_43650923/article/details/102160310