简体   繁体   中英

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

Let's say that I have an HTML structure like this:

<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 . 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). 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)? 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/

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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