JS阻止表單提交


問題:在彈出提示框點擊確定后,即使格式錯誤再次點擊提交依然會提交

解決方法:在表單第一行要這樣引用:

<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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM