javascript - 在 HTML 中添加数值

标签 javascript html

我有这个 HTML 和 Java 脚本。我正在设置自动显示这 3 个输入字段的总金额。但是如果我使用 + (添加),它会给我错误的答案。如果我使用 *(乘法)或/(除法)我工作得很好。任何人都请帮助!

这是我的 HTML 代码。

</pre>
    <tr>
        <td><input type='number' id='amt1' name='amt1' onkeyup='total_amount();' onKeyUp='return numbersonly(event);' class='form-control'></td>
        <td><input type='number' id='amt2' name='amt2' onkeyup='total_amount();' onKeyUp='return numbersonly(event);' class='form-control'></td>
        <td><input type='number' id='amt3' name='amt3' onkeyup='total_amount();' onKeyUp='return numbersonly(event);' class='form-control'></td>
        <td><input type='number' id='total' name='total' class='form-control' readonly='readonly'></td>
    </tr>
<pre>

这是我的 Java 脚本...

<script type="text/javascript">

    function total_amount()
    {
        document.getElementById('total').value = document.getElementById('amt1').value + document.getElementById('amt2').value + document.getElementById('amt3').value
    }

    function numbersonly(e){
       var unicode=e.charCode? e.charCode : e.keyCode
       if (unicode!=8 && unicode!=46 && unicode!=37 && unicode!=27 && unicode!=38 && unicode!=39 && unicode!=40 && unicode!=9){ //if the key isn't the backspace key (which we should allow)
           if (unicode<48||unicode>57)
               return false
        }
    }

</script>
</pre>

最佳答案

保持简单。使用 event delegation和一个 keyUp 处理程序。不要使用内联处理程序。在使用它进行计算之前,将字段值转换为 Number。这是一个例子:

document.querySelector('table').addEventListener('keyup', sum);

function sum(e) {
  var from = e.target || e.srcElement
     ,isNumericInput = /number/i.test(from.type);
  if (!isNumericInput) {return true;}
  var d = document
     ,inputs = d.querySelector('table').querySelectorAll('[type=number]')
     ,sumfld = d.querySelector('#sum')
     ,sumnow = 0;
  
  [].forEach.call(inputs,
                  function (v) {
                      sumnow += +(v.value); //<= conversion to Number, using +
                   });
  
  sumfld.textContent = sumnow;
}
<table>
  <tr>
   <td><input type='number' id='amt1' name='amt1' class='form-control'></td>
   <td><input type='number' id='amt2' name='amt2' class='form-control'></td>
   <td><input type='number' id='amt3' name='amt3' class='form-control'></td>
   <td><b>Total</b>: <span id="sum"></span></td>
  </tr>
</table>

关于javascript - 在 HTML 中添加数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26155251/

相关文章:

html - 将标题 1 和标题 2 移动到图像右侧

jquery - 高度变化时创建可滚动的 overflow-y?

html - CSS 列表菜单翻转填充/边距

javascript - 使用键盘制表键 tabindex 元素未显示

html - 是否可以将 google adsense 添加到 Bitbucket 页面

javascript - 使用 Isotope 的 smartresize() 使 div 流畅

JavaScript 缩短 GET 值

Javascript:如何检查用户是否更改域?

javascript - 我无法到达 "/campgrounds/:id/comments/new"

php - 如何通过更改选择来更改输入(文本框)中的值