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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mark_to_win

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值