[英]JavaScript multiple inputs onChange
我有一個問題。 在基於Zend框架的應用程序中有一個購物車(如表所示)。 每行都是購物籃中的產品。 每行都有兩個表單字段:數量和價值(=價格*數量)。
我想通過JavaScript的onChange
事件按數量(價格*數量)更改值,但我不知道如何使用行數> 1來執行此操作。在Zend視圖的foreach
循環中提供了輸入。
JavaScript中是否有通用算法可以解決此問題?
每個值字段是否具有例如可以從數量字段的ID派生的ID屬性? 如果是這樣,那將是非常快捷和輕松的。 鑒於:
<table id="basket">
<tr class="basket-row">
<td class="basket-quantity">
<input type="text" id="product1234_quantity">
</td>
<td class="basket-subtotal">
<input type="hidden" id="product1234_unitprice" value="20">
<input type="text" readonly="readonly" id="product1234_subtotal">
</td>
</tr>
<tr class="basket-row">
<td class="basket-quantity">
<input type="text" id="product5678_quantity">
</td>
<td class="basket-subtotal">
<input type="hidden" id="product5678_unitprice" value="30">
<input type="text" readonly="readonly" id="product5678_subtotal">
</td>
</tr>
</table>
在這里,每種產品的單價都處於隱藏屬性中,但是我不知道您的購物車將其存儲在何處。 假設您可以從某處獲取它,並假設使用jQuery。
$('#basket').on('change','.basket-quantity input',function(e) {
$('#'+this.id.replace('_quantity','_subtotal')).val(Number($('#'this.id.replace('_quantity','_unitprice')))*Number(this.value));
});
如果您不能從其他ID派生ID,則必須進行一些更復雜的DOM查詢,但要點是,在處理程序運行時,必須確定要更新的輸入。
您沒有指定要使用的框架(如果有)。 在普通的JS中,這將需要大量額外的代碼來使其跨瀏覽器兼容,以規范事件的附加和處理。
在每個您可以使用的
$(this).index()
例如
$("#jieguo_qian table tr:nth-child(4) td").each(function(){
var tindex = $(this).index() + 1;
這樣您就可以在差異tr中獲得相同的td
th th th
td td td
td td td
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.