亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用java腳本動態乘以2個單元格并在第三個單元格中顯示結果

使用java腳本動態乘以2個單元格并在第三個單元格中顯示結果

互換的青春 2024-01-22 20:45:45
我從數據庫中提取記錄,將它們顯示在帶有表單輸入字段的表行中。這意味著將會有多行,如下面的示例 html 代碼所示。我只想使用 JavaScript。這個想法是,當用戶輸入數量時,它會乘以單價,結果顯示在小計字段中。我不是 JS 開發人員,我搜索并找到了下面的代碼,它接近我需要的代碼。如果有人可以提出一些建議以使該代碼正常工作,我將不勝感激。  <SCRIPT language="JavaScript"><!-- function calculate() {    var Quantity = document.getElementsByName("Quantity").value;    var unitPrice = document.getElementsByName("unitPrice").value;    var total = 0;    for (var i = 0; i < Quantity.length; i++) {            total += parseInt(Quantity[i].value) * parseInt(unitPrice[i]);    } document.getElementsByName("subtotal").value = total;} </SCRIPT> <table> <tr><td>  <input onblur="calculate()" name="Quantity" size="2" /> <input name="unitPrice" value="5" size="2"/><input name="subtotal" size="2"/>   </td>  </tr> <tr><td>  <input onblur="calculate()" name="Quantity" size="2" /> <input name="unitPrice" value="5" size="2"/><input name="subtotal" size="2"/>  </td>  </tr>  </table>
查看完整描述

1 回答

?
阿波羅的戰車

TA貢獻1862條經驗 獲得超6個贊

有幾點:a)document.getElementsByName("")返回一個 NodeList 元素集合,因此您無法像這樣獲取每個輸入的值,您必須在 for 循環內獲取它們;b) 然后您還需要在解析之前獲取unitPrice[i]循環內每個值的值,c) 每次迭代后應重置總數,因此可以將其放在循環內。見下文:


function calculate() {

  var Quantity = document.getElementsByName("Quantity");

  var unitPrice = document.getElementsByName("unitPrice");

  for (var i = 0; i < Quantity.length; i++) {

    if (!Quantity[i].value) continue; // prevent NaN

    let total = parseInt(Quantity[i].value) * parseInt(unitPrice[i].value);

    document.getElementsByName("subtotal")[i].value = total;

  }

}

<table>

  <tr>

    <td>

      <input onblur="calculate()" name="Quantity" size="2" />

      <input name="unitPrice" value="5" size="2" />

      <input name="subtotal" size="2" />

    </td>

  </tr>


  <tr>

    <td>

      <input onblur="calculate()" name="Quantity" size="2" />

      <input name="unitPrice" value="5" size="2" />

      <input name="subtotal" size="2" />

    </td>

  </tr>

</table>

為了避免得到NaN沒有任何值的結果,您可以添加if (!Quantity[i].value) continue;為 for 循環中的第一行,這應該可以防止它。



查看完整回答
反對 回復 2024-01-22
  • 1 回答
  • 0 關注
  • 160 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號