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

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

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

<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" οnclick="check()" value="提交" >
</form>

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

根据input的类型进行相应的选择,一般建议使用button,

<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" οnsubmit="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>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值