我想更新特定的文本框值

I want to update specific textbox value

本文关键字:文本 更新      更新时间:2023-09-26

我有一些数据库结果,我在表单中填充它们,我有这样的代码:

<input type='button' name='add' onclick='javascript: addQty();' value='+'/>
<span><?php echo $records['ct_qty']; ?></span>
<input type="text" class="gridder_input" name="quant[]" class="quant" id="quant[]" />
<input type='button' name='subtract' onclick='javascript: subtractQty();' value='-'/>

所以我想在用户按下"quant"按钮时更新特定的行:

function addQty() {
    document.getElementById("quant").value++;
}
function subtractQty() {
    if (document.getElementById("quant").value - 1 < 0) {
        return;
    } else {
        document.getElementById("quant").value--;
    }
    updateQuantity();
}

当我有一行时,这段代码可以工作,当我有两行或更多行时,没有任何工作,所以我可能需要使用这个词或其他东西?

您可以使用同级选择器来定位最近的输入。

function addQty(elm) {
  elm.nextElementSibling.nextElementSibling.value++;
}
function subtractQty(elm) {
  if (elm.previousElementSibling.value - 1 < 0) {
    return;
  } else {
    elm.previousElementSibling.value--;
  }
  updateQuantity();
}
<input type='button' name='add' onclick='javascript: addQty(this);' value='+' />
<span><?php echo $records['ct_qty']; ?></span>
<input type="text" class="gridder_input" name="quant[]" class="quant" id="quant[]" />
<input type='button' name='subtract' onclick='javascript: subtractQty(this);' value='-' />

好吧,我没有一个足够好的代码示例,但这应该足以让你在正确的方向…

function getTotals() {
  var table = document.getElementById('mytable');
  for (i = 0; i < table.rows.length; i++) {
    var quant = table.rows[i].querySelector('input[name="quant"]').value;
    var priceoriginal = table.rows[i].querySelector('input[name="priceoriginal"]').value;
    table.rows[i].querySelector('input[name="total"]').value = quant * priceoriginal;
  }
}
<table id="mytable">
  <tr>
    <td>
      <input name="quant" type="text" value="2">
    </td>
    <td>
      <input name="priceoriginal" type="text" value="6">
    </td>
    <td>Total:
      <input name="total" type="text">
    </td>
  </tr>
  <tr>
    <td>
      <input name="quant" type="text" value="8">
    </td>
    <td>
      <input name="priceoriginal" type="text" value="4">
    </td>
    <td>Total:
      <input name="total" type="text">
    </td>
  </tr>
  <tr>
    <td>
      <input name="quant" type="text" value="5">
    </td>
    <td>
      <input name="priceoriginal" type="text" value="3">
    </td>
    <td>Total:
      <input name="total" type="text">
    </td>
  </tr>
</table>
<button onclick="getTotals()">Calculate Totals</button>