Form表單驗證


Form表單提交前js驗證

1. Onclick()

2. Onsubmit()

Button標簽 input (屬性 submit  button )標簽

Input type=button   定義按鈕,沒有任何行為。多數情況下,用於通過javascript啟動腳本

Input type=submit 定義提交按鈕,提交按鈕會把表單數據發送到服務器

 

1. onclick  與 Input type=submit 搭配  

<form action=”XXXX”  method=”post” >

<input type=”text”  name=”nihao” >

<input type=”submit”  value=”提交”   onclick=”return check(this.from)  ” >

</form>

Function check(form){

//這個form參數代表html中的表單元素集合

Form.nihao代表是 <input type=”text”  name=”nihao” >真個標簽

Var  info =form.nihao.value;

 

}

 

在javascript中,事件調用函數時,用return返回值實際上是對window.event.returnValue進行設置

而該值決定當前操作是否繼續,true是繼續 false中斷

 

2.onsubmit 與 Input type=submit 搭配  

 

上述兩種方法的  Input type=submit 等同於 button標簽

 

 

 

 

3.onclick 與 Input type=button 搭配  

 

注意:Input type=button 提交不會觸發form的 onsubmit事件

 

4.html form表單提交前驗證

可以使用form表單的onsubmit方法,在提交表單之前,對表單或者網頁中的數據進行檢驗。

onsubmit指定的方法返回true,則提交數據;返回false不提交數據。

直接看下面的代碼:

復制代碼
 1 <HTML>
 2     <head>
 3         <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 4     </head>
 5     <BODY>
 6         <form action="http://www.baidu.com" onsubmit="return toVaild()">
 7             <input type="text" id="ff">
 8             <input type="submit" id="submit" value ="提交"/>
 9         </form>
10     </BODY>
11         <script language="javascript">
12             function toVaild(){
13                 var val = document.getElementById("ff").value;
14                 alert(val);
15                 if(val == "可以提交"){
16                     alert("校驗成功,之后進行提交");
17                     return true;
18                 }
19                 else{
20                     alert("校驗失敗,不進行提交");
21                     return false;
22                 }
23             }
24     </script>
25 </HTML>
復制代碼

上面的網頁中,只有在id="ff"的輸入框中輸入“可以提交”,才進行表單提交;否則不提交。


免責聲明!

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



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