2011-08-26 8 views
6

어떻게 자바 스크립트를 사용하여 unitprice 배열에 채워진 값을 요약 할 수 있습니까 여기 내 HTML입니다.자바 스크립트 배열 합계

<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
이 (고유해야합니다 id) class 대신 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() 기능) :

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 (함수 (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 네, 정말 깨끗합니다. 나는 왜 내가 haha했던 방식으로 그것을 썼는지 확실하지 않다 – Paulpro

0

<input>님께 고유 한 아이디를주세요. 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를 사용할 필요가 없습니다 :

<input type="text" id="unitprice_1"> 
<input type="text" id="unitprice_2"> 
<input type="text" id="unitprice_3"> 

그런 다음 합계를 계산합니다. 배열 객체에 이미있는 메소드를 사용하여 작업을 수행 할 수 있습니다.

배열에는 .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

이 답변은 더 많은 인정을받을 자격이 있습니다. 고마워. – backdesk

+1

람다를 사용 : var sum = sampleArray.reduce ((e, i) => e + i)' – aloisdg