数字递增按钮

number increment button

我有一个现有的 html 表单,它使用数组来存储多行值。所以我没有不同行的同一字段的特定名称。在 PHP 页面中,我根据索引匹配行。 在下面的表格中,如何让按钮+和-来增加和减少特定行的数量值?

第 1 行

<input type="text" name="product[]" />
<input type="text" name="price[]" value="" onChange="updatePrice()" />
<input type="text" name="quantity[]" value="" onChange="updatePrice()" />
<input type="button"  onclick="inc(this)" value="+"/>
<input type="button"  onclick="dec(this)" value="-"/>`

第 2 行

<input type="text" name="product[]" />
<input type="text" name="price[]" value="" onChange="updatePrice()" />
<input type="text" name="quantity[]" value="" onChange="updatePrice()" />
<input type="button"  onclick="inc(this)" value="+"/>
<input type="button"  onclick="dec(this)" value="-"/>

第 3 行

<input type="text" name="product[]" />
<input type="text" name="price[]" value="" onChange="updatePrice()" />
<input type="text" name="quantity[]" value="" onChange="updatePrice()" />
<input type="button"  onclick="inc(this)" value="+"/>
<input type="button"  onclick="dec(this)" value="-"/>

在我看来你首先应该计算项目:

<input type="text" name="product[]" />
<input id="price-1" type="text" name="price[]" value="" onChange="updatePrice(1)" /> <!-- row number -->
<input id="qty-1" type="text" name="quantity[]" value="" onChange="updatePrice(1)" />
<input type="button"  onclick="inc('qty-1')" value="+"/>
<input type="button"  onclick="dec('qty-1')" value="-"/>

然后使用javascript操作物品:

<script>
function inc(id) {
  stepQty(id, +1);
}
function dec(id) {
  stepQty(id, -1);
}
function stepQty(id, step) {
  var value = $('#'+id).val();
  $('#'+id).val(value + step);
}
function updatePrice(id) {
  var a = $('#price-'+id).val() || 0;
  var b = $('#qty-'+id).val() || 0;
  $('#'+id).val(a*b);
}
</script>