2013-03-04 65 views
1

我是一個新手到javascript,我不能返回該函數的布爾值..我驗證文本框爲null,並返回false,如果它的空幫助請?jquery錯誤與返回布爾值

validateForm : function() { 
    $('.requiredField :input').each(function(){ 
     if ('input[type=text]'){ 
      if($(this).val().length === 0){ 
        $(this).addClass('warning'); 
        var errorMsg = $('<br /><span>Please Fill in the TextBox</span>').addClass('warning'); 
        errorMsg.insertAfter(this); 
        $(errorMsg).css('color','red'); 
        $('.warning').css('border-color','red'); 
      //$(this).focus(function(){ 
       //$(this).removeClass('warning'); 
       //$(this).parent().children('span').remove(); 
       //$(this).parent().children('br').remove();   
      //}); 
        return false; 
       } 
      else 
       return true; 
      } 
     }); 

}, 
Form.validateForm(); // call to the function 
+0

你得到一個錯誤信息? – Kaf 2013-03-04 17:46:56

+0

@Kaf沒有消息或沒有錯誤 – inputError 2013-03-04 17:47:59

+1

返回false到哪裏?你只是在執行這個函數。 – Popnoodles 2013-03-04 17:48:20

回答

2

您是return荷蘭國際集團從.each()。這不會讓你的函數返回一個值。

.each()循環,return false;就像使用break;,和return true;就像使用continue;

您需要申報.each()的變量,設置裏面其價值循環,然後返回它循環之後。

0

檢查此行

if ('input[type=text]'){ 

應該

if($('input[type=text]')){ 
0

你可以試試這個:

$('.requiredField :input').each(function(){ 
var i=$(this).val(); 

if(i == '' || i == null) 
{ 
//execute your codes 
return false; 
}else{ 
return true; 
} 
}); 
0

看來你正試圖寫一個插件?試試下面的代碼:

(function($) { 
    $.fn.validateForm = function() 
    { 
     var formID = $(this).attr('id'); 

     $('#'+ formID +' input[type=submit]').click(function(e) 
     { 

      e.preventDefault(); 

      $('input[type=text]').each(function(){ 

       if($(this).val().length === 0){     

         $(this).addClass('warning'); 
         var errorMsg = $('<span>Please Fill in the TextBox</span>').addClass('warning'); 
         errorMsg.insertAfter(this); 
         $(errorMsg).css('color','red'); 
         $('.warning').css('border-color','red');   
         return false; 
       }else{ 
        return true; 
       } 
      }); 
     }); 
    }; 
})(jQuery); 
0

正如mentionned由@RocketHazmat,你的函數需要聚集來自內部循環的結果,爲了驗證有一個單一的出口點(並添加CSS類/ html元素)輸入。

你需要做這樣的事情:

validateForm : function() { 

     var invalidInputs = []; 

     // only test the type='text' inputs 
     $('.requiredField :input[type="text"]').each(function() { 

      // if there is no value 
      if ($(this).val() == undefined || $(this).val().length == 0) { 

       $(this).addClass('warning'); 
       var errorMsg = $('<br /><span>Please Fill in the TextBox</span>').addClass('warning'); 
       errorMsg.insertAfter(this); 
       $(errorMsg).css('color','red'); 
       $('.warning').css('border-color','red'); 

       // add the invalid input to an array 
       invalidInputs.push($(this)); 
      } 
     }); 

     // The form is only valid for no invalid inputs were found. 
     return invalidInputs.length == 0; 
    }