DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> jQuery入門知識 >> JQuery特效代碼 >> 基於jQuery實現表單提交驗證
基於jQuery實現表單提交驗證
編輯:JQuery特效代碼     

html表單代碼:
代碼如下:
   <form method="post" action="">
       <div class="int">
          <label for="username">用戶名:</label>
          <input type="text" id="username" class="required"/>
       </div>
       <div class="int">
           <label for="username">郵箱:</label>
           <input type="text" id="email" class="required"/>
       </div>
       <div class="int">
           <label for="username">個人資料:</label>
           <input type="text" id="personinfo"/>
       </div>
       <div class="sub">
           <input type="submit" value="提交" id="send"/>
           <input type="reset" id="res"/>
       </div>
   </form> 

jQuery代碼:
代碼如下:
          $(function(){
            $("form :input.required").each(function(){
                var $required = $("<strong class='high'>*</strong>");
                //$(this).parent().append($required);  //追加到文檔中
                $(this).parent().prepend($required);
            });
            $('form :input').blur(function(){
                var $parent = $(this).parent();
                if($(this).is('#username')){
                   if(this.value==""||this.value.length<6){
                      var errorMsg = '請輸入至少6位的用戶名';
                      $parent.append('<span class="formtips onError">'+errorMsg+'</span>');
                   }else{
                       var okMsg = '輸入正確';
                       $parent.append('<span class="formtips onSuccess">'+okMsg+'</span>');
                   }
                }
                if($(this).is('#email')){
                    if(this.value==""||(this.value!=""&&!/.+@.+\.[a-zA-Z]{2,4}$/.test(this.value))){
                        var errorMsg = '請輸入正確的E-mail地址';
                        $parent.append('<span class="formtips onError">'+errorMsg+'</span>');
                    }else{
                        var okMsg = '輸入正確';
                        $parent.append('<span class="formtips onSuccess">'+okMsg+'</span>');
                    }
                }
            });
            $("form :input").focus(function(){
                var $parent = $(this).parent();
                $parent.find(".formtips").remove();
            });
            $("#send").click(function(){
               var $parent = $(this).parent().parent();
               $parent.find(".formtips").remove();
               $("form .required:input").trigger('blur');
               var numError = $('form .onError').length;
               if(numError){
                  return false;
               }
            });
            $("#res").click(function(){
                var $parent = $(this).parent().parent();
                $parent.find(".formtips").remove();
            });
        });

代碼很簡單,也很易懂,小伙伴們直接拿走用吧,這裡就不詳細說明了。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved