簡體   English   中英

具有相同名稱的輸入字段的值和並單獨顯示它們

[英]Sum values of input fields with same name and display them individually

我有以下處理訂單表格的輸入字段,其中:

  1. 訂單日期在名稱字段上作為數組給出
  2. 成本在字段中給出

     <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"> 

我試圖獲得警報的輸出是:

Total amount on 09-13-2017 is 7
Total amount on 09-15-2017 is 6

這就是我目前正在嘗試的:

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);
}

我知道我做了一個糟糕的javascript腳本。 任何人都可以指導我獲得如上所示的價值觀嗎?

工作小提琴

首先, 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">

然后你可以使用一個對象來存儲一些使用輸入名稱作為關鍵字的對象:

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]);
  }
}

注意:您可以使用replace()從輸出中刪除括號[] ,如:

console.log("Total amount on " + key.replace('[]','') + " is " + totals[key]);

希望這可以幫助。

 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM