简体   繁体   中英

Check if all inputs have value of zero with JS or jQuery

I'm trying to check if ALL inputs ( .productTextInput ) have a value of zero.

If they are all zero then execute an alert, but only if they are ALL zero.

I have been able to check the first and all individually, but not all together.

HTML

<div class="container">
    <div class="listQuantity">
        <input type="text" class="productTextInput" name="AddToCart_Amount" value="0">
    </div>
    <div class="listQuantity">
        <input type="text" class="productTextInput" name="AddToCart_Amount" value="0">
    </div>
    <div class="listQuantity">
        <input type="text" class="productTextInput" name="AddToCart_Amount" value="0">
    </div>
</div>

Script

$('.productTextInput').each(function() {
    if ($(this).val() <= 1){
        alert("Must choose at least one product");
    } else {
        // do something
    }
});

You can use filter for this:

if ($('.productTextInput').filter(function() {
        return parseInt(this.value, 10) !== 0;
    }).length === 0) {
    // They all have zero
}
else {
    // At least one has a non-zero value
}
$input_val = true;
$('.productTextInput').each(function() {
    if ($.trim($(this).val()) <= 1){
        $input_val = false;
        return false;
    } else {
        // do something
    }
});

if(!$input_val){
    alert("Must choose at least one product");
}
var valid = false;
$('.productTextInput').each(function() {
    if (!valid && this.value == 1){
        valid = true;
    }
});

if(!valid){
    alert("Must choose at least one product");
}
$('.productTextInput').each(function( index, value ) {
    if (parseInt($(this).val())>0){alert("Must choose at least one product");}
});

Use a flag variable to check the case in the loop

var flag = true;
$('.productTextInput').each(function() {
    if ($(this).val() != 0){
        flag = false;
        return false
    }
});

if(!flag){
    alert('at least one is more than 0')
}

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