检查jQuery中所有字段是否为空

Check for empty a field from all in jQuery

本文关键字:是否 字段 jQuery 检查      更新时间:2023-09-26

我有四个字段,如果至少一个字段有值,我的函数返回true,如果所有字段没有值返回false,我怎么做呢?

My try:(this doesn't work like I want)

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;
}
我的建议是:
function required_eachinput(){
    var result = '';
    $('.myclass').each(function(){
        result += $(this).val();
    });
    return result != '';
}

它所做的基本上是连接所有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
}

不破坏代码:

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;
}

你不使用纯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;
    }
}
演示