[英]Sum values of input fields with same name and display them individually
I have the below input fields of a processed order form in which: 我有以下处理订单表格的输入字段,其中:
Cost is given on the value field 成本在值字段中给出
<input type="hidden" name="09-15-2017[]" id="dateprice[]" value="1"> <input type="hidden" name="09-13-2017[]" id="dateprice[]" value="3"> <input type="hidden" name="09-13-2017[]" id="dateprice[]" value="4"> <input type="hidden" name="09-15-2017[]" id="dateprice[]" value="5">
The output im trying to get as an alert is: 我试图获得警报的输出是:
Total amount on 09-13-2017 is 7
Total amount on 09-15-2017 is 6
This what im currently trying: 这就是我目前正在尝试的:
var chkprice = 0;
var chkdate = 0;
var inps = document.getElementsByID('dateprice[]');
for (var i = 0; i <inps.length; i++)
{
var inp=inps[i];
var chkprice = inp.value;
if(chkdate==chkdate)
{
chkprice +=chkprice;
}
alert("Total amount on "+chkdate+""+chkprice);
alert(chkprice);
}
I know i have done a terrible javascript scripting. 我知道我做了一个糟糕的javascript脚本。 Can any one guide me in getting values as shown above?
任何人都可以指导我获得如上所示的价值观吗?
Working fiddle . 工作小提琴 。
First of all the id
attribute should be unique in the same document so you could use the common classes instead like : 首先,
id
属性在同一文档中应该是唯一的,因此您可以使用公共类,如:
<input type="hidden" name="09-15-2017[]" class="dateprice" value="1">
<input type="hidden" name="09-13-2017[]" class="dateprice" value="3">
<input type="hidden" name="09-13-2017[]" class="dateprice" value="4">
<input type="hidden" name="09-15-2017[]" class="dateprice" value="5">
Then you could use an object to store the some using the name of inputs as key like : 然后你可以使用一个对象来存储一些使用输入名称作为关键字的对象:
var inps = document.querySelectorAll('.dateprice');
var totals = {};
//Sum calculation
for (var i = 0; i <inps.length; i++)
{
totals[inps[i].name] = (totals[inps[i].name] || 0) + Number(inps[i].value);
}
//Result display
for (var key in totals) {
if (totals.hasOwnProperty(key)) {
console.log("Total amount on " + key + " is " + totals[key]);
}
}
NOTE : You coudle remove the brackets [ ] from the output using replace()
like : 注意:您可以使用
replace()
从输出中删除括号[] ,如:
console.log("Total amount on " + key.replace('[]','') + " is " + totals[key]);
Hope this helps. 希望这可以帮助。
var inps = document.querySelectorAll('.dateprice'); var totals = {}; //Sum calculation for (var i = 0; i <inps.length; i++) { totals[inps[i].name] = (totals[inps[i].name] || 0) + Number(inps[i].value); } //Result display for (var key in totals) { if (totals.hasOwnProperty(key)) { console.log("Total amount on " + key + " is " + totals[key]); } }
<input type="hidden" name="09-15-2017[]" class="dateprice" value="1"> <input type="hidden" name="09-13-2017[]" class="dateprice" value="3"> <input type="hidden" name="09-13-2017[]" class="dateprice" value="4"> <input type="hidden" name="09-15-2017[]" class="dateprice" value="5">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.