首页 > 解决方案 > 使用 Javascript 从 HTML 表单添加数字,无需提交或刷新

问题描述

您好我正在尝试使用 HTML 创建一个表单,其中用户可以在表单 1 和表单 2 中插入数字。一旦 2 个表单填充了数字,总数会自动显示在下一行,没有提交按钮。

请注意,表单是 Django Forms

这是我尝试过的。

var item_1_amount = document.getElementById("item_1_amount");
var item_2_amount = document.getElementById("item_2_amount");
var total = item_1_amount.value + item_2_amount.value
item_1_amount.onkeyup = function () {
    document.getElementById("Total").innerHTML = total.value;
};
<tr>
 <td><h6 style="float:left; margin-right:5px; margin-top:7px">$</h6>
    <input
      autocomplete="off"
      type="number"
      class="form-control w-25"
      name="item_1_amount"
      id="item_1_amount"
      style="float:left"/>
  </td>
  <td><h6 style="float:left; margin-right:5px; margin-top:7px">$</h6>
    <input
      autocomplete="off"
      type="number"
      class="form-control w-25"
      name="item_2_amount"
      id="item_2_amount"
      style="float:left"/>
  </td>
</tr>

<tr>
<th>Total</th>
<th id="Total">$$</th>
</tr>

标签: javascripthtml

解决方案


为确保仅在两个输入元素都有值时执行计算,您可以使用对象文字(或其他)跟踪输入元素的值 - 当事件处理程序注册更改时分配值。

/* shorthand utility functions */
const q=(e,n=document)=>n.querySelector(e);
const qa=(e,n=document)=>n.querySelectorAll(e);

/*
  Store values from input elements in this object. 
  When this contains exactly 2 items perform the calculations.
*/
const results={};


qa('[type="number"].form-control').forEach(input=>input.addEventListener('keyup',function(e){
  /* add the value against the id to the object described above */
  results[ this.name ]=Number( this.value );
  
  /* perfrom calculations on stored values ~ use array.reduce() to generate the SUM */
  if( Object.keys( results ).length==2 ){
    q('th#total').textContent=[ ...Object.values( results ) ].reduce((a,v)=>a+v);
  }
}));
#total:before,
label:before{content:'$'}

label{
  display:inline-block;
}
<table>
  <tr>
   <td>
     <label>
       <input autocomplete="off" type="number" class="form-control w-25" name="item_1_amount" />
     </label>
    </td>
    <td>
      <label>
        <input autocomplete="off" type="number" class="form-control w-25" name="item_2_amount" />
      </label>
    </td>
  </tr>
  <tr>
    <th>Total</th>
    <th id="total"></th>
  </tr>
</table>


推荐阅读