最近在做验证的时候遇到了submit()与onsubmit()事件冲突的问题,本来想在a标签中添加submit()进行表单的提交,然后在 form中添加onsubmit事件触发验证方法。结果行不通,最后只能选择在java script中进行表单的提交。方案如下:
设置form头部如下:添加id是为了在java script脚本中进行中获取form对象
<form method="post" action="AdminServlet" id="Loginform" >
在a标签中添加onClick()事件,触发java script表单验证的方法loginLayoutValidate()
<a href="javascript:void(0)" onClick="loginLayoutValidate()"/>
function loginLayoutValidate(){ var userName=document.getElementById("userName"); var passWord= document.getElementById("passWord"); var validateCode=document.getElementById("validateCode"); if(userName.value.trim()==""){ alert("用户名不能为空"); return ; } else if(passWord.value.trim()==""){ alert("密码不能为空"); return ; } else if(validateCode.value.trim()==""){ alert("请输入验证码"); return ; } else{ document.getElementById("Loginform").submit(); } }
例子:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script> function submitcheck() { if (document.getElementById('name').value == '') { alert('必须输入网站名!'); document.getElementById('name').focus(); return false; } else if (document.getElementById('ftp_url').value == '') { alert('必须输入Ftp地址!'); document.getElementById('ftp_url').focus(); return false; } else { document.getElementById('fm_1').submit(); } } </script> </head> <body> <form action="#" id="fm_1" name="fm_1"> <input type="text" id="name" name="name" required="required">* <br> <input type="text" id="ftp_url" name="ftp_url">* <br> <input type="submit" value="提交"> <br> <input type="reset" value="重置"> <br> <a href="javascript:void(0)" onclick="checkform()">提交</a> <br><a href="#" onclick="document.fm_1.reset()">重置</a> </form> </body> </html>