2011-08-26 21 views
6

どのように私は単位の配列に値を合計することができますjavacriptを使用して ここに私のhtmlです。JavaScriptの配列の合計

<td> 
     <input type="text" style="width: 60px; background: none repeat scroll 0% 0% rgb(255, 255, 255);" maxlength="4" id="unitprice" name="unitprice[]"> 
    </td> 
    <td> 
     <input type="text" style="width: 60px; background: none repeat scroll 0% 0% rgb(255, 255, 255);" maxlength="4" id="unitprice" name="unitprice[]"> 
    </td> 
+0

IDは**ユニーク**である必要があります! (そしてはい、できます) –

+0

'id'属性の代わりに' class'属性を使います。 (ページ上に同じIDを持つ要素を複数持つことはできません) –

+0

IDを一意にするといいですが、どうすればそれをさらに行うことができますか? Add new rowをクリックするとunitpriceが動的で、別のunitpriceが作成されることを覚えておいてください。だから私はその合計が必要です。 – Faizan

答えて

5
class代わりの idを( idは一意である必要があります)を使用して、あなたのHTMLを変更

<td> 
    <input type="text" 
     style="width: 60px; background: none repeat scroll 0% 0% rgb(255, 255, 255);" maxlength="4" 
     class="unitprice" name="unitprice[]"> 
</td> 
<td> 
    <input type="text" 
     style="width: 60px; background: none repeat scroll 0% 0% rgb(255, 255, 255);" 
      maxlength="4" class="unitprice" name="unitprice[]"> 
</td> 

その後、あなたは(jQueryの.each()機能を使用して)JavaScriptで合計することができます

var totalUnitPrice = 0; 

$('.unitprice').each(function(index) { 
    totalUnitPrice += parseInt($(this).val()); // parse the value to an Integer (otherwise it'll be concatenated as string) or use parseFloat for decimals 
    }); 
+0

非常にうまくいった!ありがとう – Faizan

+12

'var sum = arr.reduce(function(a、b){return a + b;}、0);'はjQueryのeach()より高速です。 – Riking

+0

さらに短く 'var sum = reduce((a、b)=> a + b、0); ' – evgpisarchik

2
function getSum(){ 
    var ups = document.getElementsByName('unitprice[]'), sum = 0, i; 
    for(i = ups.length; i--;) 
     if(ups[i].value) 
      sum += parseInt(ups[i].value, 10); 
    return sum; 
} 
+0

'for'ループを' for(i = ups.length; i - ;) 'と書くこともできます。 –

+0

@Felix Yeaとてもクリーンです。私はなぜ私がhahaをやったようにそれを書いたのか分からない – Paulpro

0

<input>に固有のids li KEこの:

​​

次に合計を計算:

var i = 1; 
var sum = 0; 
var input; 
while((input = document.getElementById('unitprice_'+i)) !== null) { 
    sum += parseInt(input.value); 
    ++i; 
} 
alert(sum); 
35

あなたは配列の値を得ることができる場合、あなたがそれらを合計するjQueryのを使用する必要はありません。配列オブジェクトに既に存在するメソッドを使用して作業を行うことができます。

配列には.reduce()メソッドがあります。 ドキュメント: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/Reduce

Array.reduceは、アキュムレータコールバックとして機能する引数として関数を受け入れます。 accumulator関数は、4つの引数(previousValue、currentValue、index、array)を受け取ります。合計するには2つだけ必要です。これらの2つの引数は、previousValueとcurrentValueです。

var sampleArray = [1, 2, 3, 4, 5]; 
var sum = sampleArray.reduce(function(previousValue, currentValue){ 
    return currentValue + previousValue; 
}); 

あなたがターゲット環境は、リンクされたMDNの記事で定義されたプロトタイプ定義を使用して、ECMAScriptの5以上の追加をサポートしていない互換性の問題に直面している場合。 (下付)

if (!Array.prototype.reduce) { 
    Array.prototype.reduce = function reduce(accumulator){ 
    if (this===null || this===undefined) throw new TypeError("Object is null or undefined"); 
    var i = 0, l = this.length >> 0, curr; 
    if(typeof accumulator !== "function") // ES5 : "If IsCallable(callbackfn) is false, throw a TypeError exception." 
     throw new TypeError("First argument is not callable"); 
    if(arguments.length < 2) { 
     if (l === 0) throw new TypeError("Array length is 0 and no second argument"); 
     curr = this[0]; 
     i = 1; // start accumulating at the second element 
    } 
    else 
     curr = arguments[1]; 
    while (i < l) { 
     if(i in this) curr = accumulator.call(undefined, curr, this[i], i, this); 
     ++i; 
    } 
    return curr; 
    }; 
} 
+0

私が求めていたもの。 OPの元のタイトルは少し誤解を招く。 – frostymarvelous

+0

この回答は、より多くの認識を得るに値する。ありがとうderenard。 – backdesk

+1

ラムダを使う: 'var sum = sampleArray.reduce((e、i)=> e + i)' – aloisdg