简体   繁体   English

jQuery每个循环检查是否至少填充了一个字段

[英]jquery each loop check if at least one field has been filled

Let's say that I have an HTML structure like this: 假设我有这样的HTML结构:

<input type="text" name="input_1" class="required" value="" />
<input type="text" name="input_2" class="required" value="" />
<input type="text" name="input_3" class="required one" value="" />
<input type="text" name="input_4" class="required one" value="" />
<input type="text" name="input_5" class="required" value="" />

As you can see each text field above has the class required but there are two of them that also have the class one . 正如你可以看到每个文本字段上方有一流的required ,但有两个人也有类one What I wanna do is to iterate over these text fields and check if they are not empty but for the ones that have the class one , at least one of them is required (not both at the same time). 我想要做的是遍历这些文本字段,并检查它们是否不为空,但对于具有类的那些one ,其中至少有一个是必需的(不能同时在同一时间)。 If I iterate over the input with class required , how do I check if at least one of the inputs with class one has been filled (within the same loop)? 如果我遍历了required为class的输入,如何检查是否至少有一个class one的输入已被填充(在同一循环中)? Thank you 谢谢

You can do: 你可以做:

var oneIsFilled = false;
$(":text.required").each(function() {
    if ($(this).hasClass("one") {
        if (this.value.length > 0)
            oneIsFilled = true;
    }
});

These here will additionally cover the checking of the required fields: 这些在这里还将涵盖对必填字段的检查:

Working example see my fiddle: http://jsfiddle.net/Florian_Loch/A3C5C/1/ 工作示例请参见我的提琴: http : //jsfiddle.net/Florian_Loch/A3C5C/1/

function click() {
    var bool = check();

    if (bool) {
        alert("OK!");
    } else {
        alert("NOOOO!");
    }
}

function check() {
    var one = false;
    var res = true;

    $(".required").each(function () {
        if ($(this).hasClass("one") && this.value.length > 0) {
            one = true;   
        }

        if ($(this).hasClass("required") && $(this).hasClass("one") == false && this.value.length == 0) {
            res = false;
            return; //We can leave here already
        }        
    });

    if (!res) {
        return false;
    }
    else {
        return one;
    }
}

Cheers, 干杯,
Florian 弗洛里安

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM