2012-03-03 9 views
1

我正在製作表單驗證函數並卡在某個地方,要解決問題我想獲取表單元素的總數目&也想檢查一下如果所有表單元素都被填充或不填充。
功能被稱爲模糊事件,下面是我的代碼:表單中存在的元素總數 - jQuery

(function($){ 
    $.fn.da_form_validation = function(options){   
     var error_fields = function(){ 
      var form_element_length = $(this).length; 
      alert(form_element_length); 
     }; 

     return this.each(function(){ 
      $(this).blur(error_fields); 
     }); 
    }; 
})(jQuery); 

$(".check_field").da_form_validation(); 

<form name="sample_form" method="post"> 
    <input class="check_field" type="text" name="first_name" id="first_name" value="" /> 
    <input class="check_field" type="text" name="last_name" id="last_name" value="" /> 
    <textarea class="check_field" name="address" id="address"></textarea> 
    <input type="submit" name="submitbtn" id="submitbtn" value="Submit" disabled="disabled" /> 
</form> 

注:目前提交按鈕被禁用。
所以如果以上所有表單字段都被填充,提交按鈕將被啓用。

目前,如果我試圖讓形式的長度這樣它總是給我1而不是3

請幫助。

回答

3

您正在運行error_fields函數,該函數單獨檢查.check_field中每個元素的項目數。所以當然.length將返回1


請看delegated events保存自己從模糊的事件處理程序綁定到每個不同的輸入元素。

$(function(){ 
    // register handler once! 
    $('form').on('blur', 'input, select, textarea', function(){ 
    // handle blur for all input elements of the form 

    // this refers to the form 
    alert($(this).find('input, select, textarea').length + ' input-elements in form'); 
    }); 
}); 
1

嘗試了這一點:

$('.check_field').on('blur',function(){ 
    var allFilled=true; 
    $('.check_field').each(function(){ 
     if($(this).val()===''){ 
     allFilled=false; 
     return; 
    } 
    }); 
    if(allFilled){ 
     $('#submitbtn').removeAttr("disabled"); 
    } 
});​ 

您可以在小提琴運行例如:

Code at JSFiddle

2

您可以修改代碼如下

$.fn.da_form_validation = function(options){   
     var error_fields = function(){ 

      var totalElements = jQuery('.check_field').length; 
      var form_element_length = $(this).length; 

       if($(this).val() == "") { 

       form_element_length = $(this).attr('title'); 
       $('#submitbtn').attr("disabled", 'disabled'); 
       alert(form_element_length); 


       } 
      var allFilled= true ; 
      $('.check_field').each(function(){ 
       if($(this).val()===''){ 
       allFilled=false; 
       } 
      }); 

      if(allFilled){ 
       $('#submitbtn').removeAttr("disabled"); 
      } 
      allFilled=false; 
     } 

     return this.each(function(){ 
      $(this).blur(error_fields); 

     }); 
    }; 



    $(".check_field").da_form_validation(); 


}); 
</script> 

<form name="sample_form" method="post"> 
    <input class="check_field" type="text" name="first_name" id="first_name" value="" title="Please Fill first name" /> 
    <input class="check_field" type="text" name="last_name" id="last_name" value="" title="Please Fill last name" /> 
    <textarea class="check_field" name="address" id="address" title="Please Fill addres"></textarea> 
    <input type="submit" name="submitbtn" id="submitbtn" value="Submit" disabled="disabled" /> 
</form>