[英]How to get the input value all and make an addition
<ul class="liste_couleur_qty">
<li style="margin-bottom: 20px;">
<dl>
<table width="200" border="0">
<tbody><tr>
<td width="50%">
<span style="display: block; font-size: 13px; line-height: 16px; margin-bottom: 2px;margin-right: 0px;margin-left: 20px;">Noir</span>
</td>
<td width="50%"><div class="add-to-cart">
<label for="qty-2195">qty :</label>
<input type="text" class="input-text qty calcul_qty_product" title="Qté" value="0" autocomplete="off" maxlength="5" data-product_color="127" id="qty-2195" name="qty-2195" onblur="addToCartPlus(2195, 127, this);">
</div></td>
</tr>
</tbody></table>
</dl>
</li>
<li style="margin-bottom: 20px;">
<dl>
<table width="200" border="0">
<tbody><tr>
<td width="50%">
<span style="display: block; font-size: 13px; line-height: 16px; margin-bottom: 2px;margin-right: 0px;margin-left: 20px;">Blanc</span>
</td>
<td width="50%"><div class="add-to-cart">
<label for="qty-2196">qty :</label>
<input type="text" class="input-text qty calcul_qty_product" title="Qté" value="0" autocomplete="off" maxlength="5" id="qty-2196" name="qty-2196" onblur="addToCartPlus();">
</div></td>
</tr>
</tbody></table>
</dl>
</li>
<li style="margin-bottom: 20px;">
<dl>
<table width="200" border="0">
<tbody><tr>
<td width="50%">
<span style="display: block; font-size: 13px; line-height: 16px; margin-bottom: 2px;margin-right: 0px;margin-left: 20px;">Blanc</span>
</td>
<td width="50%"><div class="add-to-cart">
<label for="qty-2196">qty :</label>
<input type="text" class="input-text qty calcul_qty_product" title="Qté" value="0" autocomplete="off" maxlength="5" id="qty-2196" name="qty-2196" onblur="addToCartPlus();">
</div></td>
</tr>
</tbody></table>
</dl>
</li>
</ul>
如何獲取所有輸入值,然后將它們全部添加,然后將其提供給變量。 如果在jQuery中,我知道該怎么辦。
var length = $('liste_couleur_qty li input').length;
var input = $('liste_couleur_qty li input').val;
for(var i=0;i< length;i++){
var result += input;
}
結果將獲得所有值。但是我的代碼仍然無法工作。我的jquery代碼出了什么問題? 如果我不想使用jQuery,請僅使用javascript。 我該怎么辦?
這應該適用於jQuery:
var result = "";
$('liste_couleur_qty li input').each(function() {
result += $(this).val();
});
首先: jQuery.val
不是屬性,而是方法。 第二:它將返回結果集中第一個元素的值,而不是所有值。 第三:在您的for循環中-我什至猜不到您要做什么。 您始終使用相同的值length
時間。 另外,一旦嘗試獲取數值,則應使用undefined提到的parseInt/parseFloat
方法
var result = 0;
$('.liste_couleur_qty li input').each(function(){
result += $(this).val();
});
console.log(result);
這並不完全准確。 正如@undefined指出的那樣,您需要使用parseInt
來執行數字加法運算而不是串聯運算。 那是:
result += parseInt($(this).val());
您的選擇器未選擇任何內容,您錯過了.
對於類選擇器,同樣val
是方法而不是屬性,可以使用each
方法和parseInt
函數:
var result = 0;
$('.liste_couleur_qty li input').each(function(){
result += parseInt(this.value, 10);
});
var length = $('liste_couleur_qty li input').length;
var input = $('liste_couleur_qty li input').val();
for(var i=0;i< length;i++){
var result += input;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.