关于form提交表单和onclick事件的触发

akiooo 2019-11-19 PM 3375℃ 0条

我们在提交的时候会对数据进行验证,在form表单的提交按钮上绑定处理JavaScript事件的问题总结。

<script type="text/javascript">
function check(){
    var password = document.getElementById("password").value;
    var pwd = document.getElementById("pwd").value;
    if(password==pwd){
        alert("验证正确");
        document.getElementById('form1').submit(); //验证成功进行表单提交
    }else{
        alert("验证错误,请重新输入");
        //window.location.href="index.jsp"; 可以将其连接到指定的位置
    }
}
</script>

<form action="deal" method="post" id="form1">
    用 户 名:<input type="text" name="username" id="username">
    密   码:<input type="password" name="password" id="password">
    确认密码:<input type="password" name="pwd" id="pwd">
<input type="button" onclick="check()" value="提交" > 
</form>

这种做法是利用按钮(注意不是submit)先进行前台验证,然后在验证成功的情况下进行表单提交,

<script type="text/javascript">
function  check2(){
    var password = document.getElementById("password").value;
    var pwd = document.getElementById("pwd").value;
    if(password==pwd){
        alert("验证正确");
        return true;
    }else{
        alert("验证错误,请重新输入");
        //window.location.href="index.jsp";  
        return false;
    }
}
</script>

<form action="deal.action" method="post" id="form1" onsubmit="return check2();">
    用  户  名:<input type="text" name="username" id="username">
    密    码:<input type="password" name="password" id="password">
    确认密码:<input type="password" name="pwd" id="pwd">
<input type="submit" value="提交" >   
</form>

方法二是利用form表单的onsubmit方法进行调用,当进行表单提交时,会先执行onsubmit( )方法,然后栽根据返回的false进行处理,注意这里只有在返回false的情况下不进行提交。

根据input的类型进行相应的选择,一般建议使用button,
————————————————
版权声明:本文为CSDN博主「發V發」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/sinat_28978689/article/details/52765583

标签: form, onclick

非特殊说明,本博所有文章均为博主原创,

部分转载有可能忘记标注,如侵犯了您的权益,您可以留言我增加原文出处或删除文档。

评论啦~