問題:在彈出提示框點擊確定后,即使格式錯誤再次點擊提交依然會提交
解決方法:在表單第一行要這樣引用:
<form id="commentForm" action="zhuce" method="post" onSubmit="return check();" name="testform">
一定要添加return,要不然提示后還是會提交;
注意:如果js中的一些Id對不上(代碼出錯),依然不能實現阻止表單提交的功能。
JavaScript代碼:
<script> function check(){ var flag = new Boolean();//布爾值沒有說明默認是true var password = document.getElementById("password").value; var repassword = document.getElementById("password1").value; if (password!=repassword){ alert("兩次輸入密碼不一致!"); // document.getElementById('password').value = ""; document.getElementById('password1').value = "";//清空原來的值 document.testform.password1.focus();//聚焦到重復密碼一欄 flag = false; } var reg = /(^\d{11}$)/; if(!reg.test(document.testform.phone.value)){//這里面testform是表單的name,phone是電話的id alert("手機號輸入不合法,應為11位數字!"); document.getElementById('phone').value="";//清空原來的值 document.testform.phone.focus();//這個是聚焦到手機一欄 flag = false; } return flag; } </script>
轉載自:https://blog.csdn.net/weixin_34074740/article/details/89871861