2011-12-03 80 views
3

我有四个字段,并且我的函数返回true,如果至少有一个字段有值,如果所有字段都没有值返回false,我该怎么做?在jQuery中检查所有空字段

我尝试:(这不起作用像我想)

function required_eachinput(){ 
    result = true; 
    $('.myclass').each(function(){ 
     var $val = $(this).val(); 
     var ok = $val.each(function(){}); 
     alert(ok); 
     if(!$val){ 
      $(this).css("background", "#ffc4c4"); 
      result = false; 
     } 
     $(this).keyup(function() { 
      $(this).closest('form').find('input').css("background", "#FFFFEC"); 
     }) 
    }); 
     return result; 
} 

回答

4

我的建议是:

function required_eachinput(){ 
    var result = ''; 
    $('.myclass').each(function(){ 
     result += $(this).val(); 
    }); 
    return result != ''; 
} 

它所做的基本上是连击所有的所有4个值字段(可以是任何数量的字段)。如果结果不是空字符串,则意味着至少有一个字段有值。否则,全部都是空的。

+0

观音赛义德一月 –

+0

@Kate,farsi baladi? kojaee hasti? –

+0

是的,mazandaran。 –

4

您可以过滤出空的元素,并检查是否有任何遗漏:http://jsfiddle.net/bbFA6/1/

function required_eachinput() { 
    return $(".myclass").filter(function() { 
     return $(this).val() !== ""; // only keep non-empty elements 
    }).length > 0; // check whether you have any non-empty elements left 
} 
1

没有破坏你的代码:

function required_eachinput(){ 
    result = false; // Start with false 
    $('.myclass').each(function(){ 
     var $val = $(this).val(); 
     if($val){ 
      result = true; // If any is not empty return true 
     } else { 
      $(this).css("background", "#ffc4c4"); 
     } 
     $(this).keyup(function() { 
      $(this).closest('form').find('input').css("background", "#FFFFEC"); 
     }); 
    }); 
    return result; 
} 
1

ŸüNO USE普通的JavaScript时,你可以?

function required_eachinput(){ 
    var inputs = document.querySelectorAll('.myclass'); 
    for(var i = 0, len = inputs.length; i < len; i++){ 
     if(inputs[i].value !== ''){ 
      return true; 
     } 
     return false; 
    } 
} 

Demo

+0

您可以随时使用普通的JvaScript;图书馆只是为了方便:) – pimvdb