【问题标题】:Sum input fields by using javascript [duplicate]使用javascript对输入字段求和[重复]
【发布时间】:2013-04-12 04:37:52
【问题描述】:

我怎样才能(通过每个函数)自动对字段求和以对一些输入字段求和:

<input name="price_1" id="price_1" type="text" value="50" />
<input name="price_2" id="price_2" type="text" value="40" />
<input name="price_3" id="price_3" type="text" value="20" />
<input name="price_4" id="price_4" type="text" value="10" />
<input name="price_5" id="price_5" type="text" value="80" />

如果有人有建议,非常感谢?

【问题讨论】:

  • 选择输入...获取值...添加它们。有什么问题?
  • 好吧,我写得不够清楚。我每行有多个输入字段,这就是为什么我需要从特定输入字段中捕获值的原因。对于这个例子,它是 id="price_[]"。

标签: javascript sum each


【解决方案1】:

使用 jQuery;

<script src="{path to jquery}/resources/js/vendor/jquery-1.9.0.min.js"></script>
<script>
$(document).ready(function() {
 var total = 0;
 $.each($('input'), function(){
   total += parseInt($(this).val(), 10); //use radix 10 to ensure correct parseInt val
 });
 console.log(total);
});
</script> 

【讨论】:

  • 你确定要求和的值是整数吗?以及为什么 jquery,一个完整的库来完成如此微不足道的任务。
  • 哈!帮自己一个忙,将 jQuery 添加到您的项目中。它超轻量级,地球上超过一半的 Web 开发人员都在使用它。诚然,您可以在没有的情况下执行此操作,并且您可能希望检查并跳过非数字的求和值。只是为了一个简洁易读的解决方案。你的也很酷。
  • 我对 jquery 没有任何问题,我喜欢它并在适当的时候使用它,现在似乎每个人都试图将它用于所有事情,而 JavaScript 的基础艺术却被忽视了。 Javascript 也很漂亮、功能强大且可读性强,如果没有它,jquery 会在哪里呢? ;)
  • 只是作为一个比较,看看我们建议的这个jsperf(jsperf.com/jq-sum-elements-vs-raw-js),纯javascript也是给每个输入元素添加了一个事件监听器。
【解决方案2】:

开启jsfiddle

<input name="price_1" id="price_1" type="text" value="50" />
<input name="price_2" id="price_2" type="text" value="40" />
<input name="price_3" id="price_3" type="text" value="20" />
<input name="price_4" id="price_4" type="text" value="10" />
<input name="price_5" id="price_5" type="text" value="80" />

var inputs = document.getElementsByTagName("input");

function sumIt() {
    var sum = Array.prototype.reduce.call(inputs, function (a, b) {
        return a + parseFloat(b.value);
    }, 0);

    console.log(sum);
}

Array.prototype.forEach.call(inputs, function (input) {
    input.addEventListener("keyup", sumIt, false);
});

【讨论】:

    猜你喜欢
    • 2017-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-04
    • 1970-01-01
    • 1970-01-01
    • 2013-04-02
    • 2016-11-27
    相关资源
    最近更新 更多