javascript 使用 JS 或 jQuery 检查所有输入的值是否为零
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16646144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if all inputs have value of zero with JS or jQuery
提问by Justin
I'm trying to check if ALL inputs (.productTextInput
) have a value of zero.
我正在尝试检查所有输入 ( .productTextInput
) 的值是否为零。
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
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
}
});
回答by T.J. Crowder
回答by Pank
$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");
}
回答by Fury
$('.productTextInput').each(function( index, value ) {
if (parseInt($(this).val())>0){alert("Must choose at least one product");}
});
回答by Kevin Bowersox
var valid = false;
$('.productTextInput').each(function() {
if (!valid && this.value == 1){
valid = true;
}
});
if(!valid){
alert("Must choose at least one product");
}
回答by Arun P Johny
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')
}