jQuery表單驗證簡單程式碼例項

admin發表於2017-02-28

表單驗證複雜程度是不同的,程式碼的複雜程度也有所不同,下面是一個比較簡單的表單驗證程式碼,對一些比較簡單的需求還是比較實用的,程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script> 
<script type="text/javascript"> 
$(document).ready(function(){ 
  $("#myform").submit(function(){ 
    var username=$("#name").val(); 
    var age=$("#age").val(); 
    var sex=$("input[name ='sex'][checked]").val(); 
    var address=$("#add option[selected]").val(); 
    var size=$("input[name='checkbox'][checked]").size(); 
    var favouriteArray=Array(size); 
    $("input[name='checkbox'][checked]").each(function(index,docEl){ 
      favouriteArray[index]=$(this).val();// or docEl.value 
    }); 
    if(username=="") { 
      alert("性名不能為空!"); 
      $("#name").focus(); 
      return false; 
    } 
    if(age=="") { 
      alert("年齡不能為空"); 
      $("#age").focus(); 
      return false; 
    } 
    if(size==0) { 
      alert("您還沒有選擇愛好哦!"); 
      $("input[name='checkbox']").get(0).focus(); 
      return false; 
    } 
    for(var i=0;i<favouriteArray.length;i++){ 
      alert(favouriteArray<i>); 
    } 
    alert('提交成功!'); 
  })
})
</script>
</head>
<body>
<form action="" method="post" id ="myform">
  <table>
    <tr>
      <td>姓名:</td>
      <td><input type ="text" id = "name" name ="name"></td>
    </tr>
    <tr>
      <td>年齡:</td>
      <td><input type ="text" id="age" name ="age"></td>
    </tr>
    <tr>
      <td>性別:</td>
      <td><input type = "radio" id="sex_man" name="sex" value="男">
        男
        <input type = "radio" id="sex_woman" name="sex" value = "女" checked ="checked">
        女</td>
    </tr>
    <tr>
      <td>地址:</td>
      <td><select id = "add">
          <option values="北京">北京</option>
          <option values="河南">河北</option>
          <option values="河南">河南</option>
        </select></td>
    </tr>
    <tr>
      <td>愛好:</td>
      <td><input type ="checkbox" id = "cbOnTheInternet" name="checkbox" value ="上網" checked="checked">
        上網
        <input type ="checkbox" id = "cbJuketing" name="checkbox" value="旅遊">
        旅遊
        <input type ="checkbox" id = "cbWatchingTv" name="checkbox" value="看電影">
        看電影 </td>
    </tr>
    <tr>
      <td><input type ="submit" value="提交"></td>
    </tr>
  </table>
</form>
</body>
</html>

以上程式碼實現了簡單的表單驗證,如果表單填寫不符合要求會彈出提示。

相關閱讀:

(1).submit事件參閱jQuery submit事件一章節。

(2).val()參閱jQuery val()方法一章節。

(3).[name ='sex']參閱jQuery [attribute=value]一章節。

(4).each()參閱jQuery each()一章節。

(5).focus()參閱jQuery focus事件一章節。

(7).get()參閱jQuery get()一章節。

相關文章