2013-05-20 128 views
2

我試圖檢查所有輸入(.productTextInput)的值是否爲零。用JS或jQuery檢查所有輸入值是否爲零

如果它們都爲零,則執行警報,但前提是它們全部爲零。

我已經能夠檢查第一個和所有單獨的,但不是全部一起。

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> 

腳本

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

之前有人張貼它尚未** **再次:( 'productTextInput [值= 「0」]')不,你不能用'$'這一點,它會檢​​查*屬性*,而不是用戶輸入的內容:[證明](http://jsbin.com/okosak/4)([source](http://jsbin.com/okosak/4/edit))輸入非-zero的值,然後點擊按鈕。 –

回答

7

您可以使用filter此:

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 
} 
+0

+1 - 也比'.each'更快 - http://jsperf.com/test-case122 –

+1

@DarrenDavies:是的。 :-)但是如果你改變'.each'測試來使用'this.value'而不是完全不必要的'$(this).val()',它幾乎會迎頭趕上:http://jsperf.com/test -case122/2(並不是說速度可能在這裏很重要。) –

+0

完全適合我需要的東西,謝謝:) – Justin

0

使用標誌變量來檢查在循環的情況下

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

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

@ T.J.Crowder是修復問題 –

1
var valid = false; 
$('.productTextInput').each(function() { 
    if (!valid && this.value == 1){ 
     valid = true; 
    } 
}); 

if(!valid){ 
    alert("Must choose at least one product"); 
} 
+0

邏輯不正確,不是嗎?看到我對Arun的回答(它實際上有相同的代碼)的評論。 –

+0

是的,即使其中一個框顯示警告!0:http://jsbin.com/okosak/2/edit –

+0

Arun現在修復了他的問題,所以這裏是我上面提到的評論(我現在已經注意到了刪除):*「該邏輯不正確,不是嗎?您使用flag = true來表示它們全部爲0,但是如果它們中的任何一個<= 1,則將您的標誌設置爲false。 (另外,<= 1和=== 0之間有很大的區別)「* –

6
$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"); 
} 
1
$('.productTextInput').each(function(index, value) { 
    if (parseInt($(this).val())>0){alert("Must choose at least one product");} 
});