Reputation: 329
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
}
});
Upvotes: 3
Views: 16265
Reputation: 94469
var valid = false;
$('.productTextInput').each(function() {
if (!valid && this.value == 1){
valid = true;
}
});
if(!valid){
alert("Must choose at least one product");
}
Upvotes: 1
Reputation: 4776
$('.productTextInput').each(function( index, value ) {
if (parseInt($(this).val())>0){alert("Must choose at least one product");}
});
Upvotes: 1
Reputation: 388316
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')
}
Upvotes: 0
Reputation: 14268
$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");
}
Upvotes: 6
Reputation: 1074355
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
}
Upvotes: 10