这段代码在<form>中有οnsubmit="return on_submit()",如果 onsubmit ()返回 fasle,表单的元素就不会提交,即action="regist.php"不会执行,如果该函数返回其他值或什么都没有返回,则表单会被提交,即执行action="regist.jsp"。也就是说,onsubmit是用来验证输入信息,而action是提供一个表单完成被提交的路径,当onsubmit为false时表单不会提交。
<form method="post" name="form" action="register.php" onSubmit="return beforeSubmit(this);">
<script type="text/javascript"> function beforeSubmit(form){ ... } </script>
例子:
<fieldset> <legend>用户注册</legend> <form method="post" name="form" action="user.do?method=register" onSubmit="return beforeSubmit(this);"> <table border="1" width="100%" cellspacing="0" cellpadding="0"> <tr><td><label>用户名:<input type="text" name="username" value=""></label></td></tr> <tr><td><label>密 码:<input type="password" name="password" value=""></label></td></tr> <tr><td><label>重复密码:<input type="password" name="password2" value=""></label></td></tr> <tr><td><input value="注册" type="submit"> <input type="reset" value="重置"></td></tr> </table> </form> </fieldset> <script type="text/javascript"> function beforeSubmit(form){ if(form.username.value==''){ alert('用户名不能为空!'); form.username.focus(); return false; } if(form.password.value==''){ alert('密码不能为空!'); form.password.focus(); return false; } if(form.password.value.length<6){ alert('密码至少为6位,请重新输入!'); form.password.focus(); return false; } if(form.password.value!=form.password2.value) { alert('你两次输入的密码不一致,请重新输入!'); form.password2.focus(); return false; } return true; } </script>