本文透過實例分析 JS 兩種類型的表單提交方法,分享給大家參考,具體如下:
1. 原始的
<form method="post" action="/student/stureg/add" id="form1" onsubmit="return subForm();"> <button type="submit" class="button red" style="font-size:18px; font-family:'微軟雅黑';">提 交</button>
這裡的 button 提交之後,會執行 subForm() 方法。subForm 可以對表單進行驗證,回傳 false 時表單不提交,否則提交。
function subForm() { var flag = true; $(".required").each(function(){ if(!$(this).val()) { flag = false; $(this).css({ border: "1px solid #F56939",borderRadius:"5px",color:"#F56939",height:"26px"}); $(this).attr("status","1").val("此處為必填項,請您填寫!"); } }); /*$(".idCardNo").each(function(){ if(!idCardNo($(this).val())) { flag = false; $(this).css({ border: "1px solid #F56939",borderRadius:"5px",color:"#F56939",height:"26px"}); if($(this).attr("status")!=1){ $(this).attr("status","1").val("請填寫正確的身份證號碼!"); } } });*/ var reg = new RegExp("^[0-9]*$"); $(".number").each(function(){ if(!reg.test($(this).val())) { flag = false; $(this).css({ border: "1px solid #F56939",borderRadius:"5px",color:"#F56939",height:"26px"}); if($(this).attr("status")!=1){ $(this).attr("status","1").val("請填寫正確的聯系電話!"); } } }); $(".exCardNo").each(function(){ if(exCardNo($(this).val())==1) { flag = false; $(this).css({ border: "1px solid #F56939",borderRadius:"5px",color:"#F56939",height:"26px"}); if($(this).attr("status")!=1){ $(this).attr("status","1").val("此身份證已報名!"); } } }); return flag; } 各種驗證都在這裡完成。
2. 以 JS 設定的提交
<form method="post" action="/student/stureg/reglogin" id="form_login"> <a id="submit"><img src="/images/login/login_bt.png" style="cursor:pointer"/></a>
這裡並不是提交按鈕,而是一個模擬提交的按鈕。
$("#submit").click(function(){ if(loginForm()) { $("#form_login").submit(); } }); 觸發提交事件時,若改用 onsubmit="return loginForm();" 就沒有效果了,因為不管是否回傳 false 都會提交。所以要在真正提交之前先做驗證。
function loginForm(){ var flag = true; $(".notnull").each(function(){ if(!$(this).val()) { flag = false; $(this).css({ border: "1px solid #F56939",borderRadius:"5px",color:"#F56939",height:"26px"}); $(this).attr("status","1").val("不能為空"); } }); return flag; } 回傳 false,就不呼叫 submit 方法。這就是兩種處理表單提交前驗證的方式。
希望本文所述對大家的 JavaScript 程式設計有所幫助。