2011-08-26 20 views
6

Cómo puedo resumir los valores completados en la matriz de precios unitarios usando javascript Aquí está mi html.Suma de matriz de 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

¡Los identificadores tienen que ser ** únicos **! (y sí, puede) –

+0

Utilice los atributos 'class' en lugar de los atributos' id'. (No puede tener más de un elemento con el mismo ID en la página.) –

+0

ok si hago ID únicos, ¿cómo puedo hacerlo? Recuerde que el precio unitario es dinámico, como hago clic en Agregar nueva fila y crea otro precio unitario. Entonces necesito su suma. – Faizan

Respuesta

5

Cambiar el código HTML para utilizar class en lugar de id (id debe ser único):

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

A continuación, se puede sumar a través de JavaScript (jQuery .each() función):

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

¡Funcionó muy bien! Gracias – Faizan

+12

'var sum = arr.reduce (function (a, b) {return a + b;}, 0);' es más rápido que jQuery's each(). – Riking

+0

O incluso más corto '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

También puede escribir el bucle 'for' como' for (i = ups.length; i -;) ' –

+0

@Felix Sí, gracias, eso es mucho más limpio. No estoy seguro de por qué lo escribí de la manera en que lo hice. Haha – Paulpro

0

Dale a tu <input> s id únicos li ke esto:

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

A continuación, calcular la suma:

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

Si usted puede conseguir los valores en una matriz, no tiene que utilizar jQuery para sumarlos. Puede usar métodos ya presentes en el objeto de matriz para hacer el trabajo.

Las matrices tienen un método .reduce(). Documentación: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/Reduce

Array.reduce acepta una función como argumento que actúa como una devolución de llamada acumulador. La función del acumulador acepta 4 argumentos (previousValue, currentValue, index, array). Solo necesitas 2 de ellos para sumar. Esos 2 argumentos son previousValue y currentValue.

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

Si usted se enfrenta con un problema de compatibilidad en el entorno de destino no es compatible con ECMAScript 5 o por encima de adiciones, utilice la definición prototipo definido en el artículo MDN vinculado. (Anexado a continuación)

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

Lo que estaba pidiendo. El título original de OP es un poco engañoso. – frostymarvelous

+0

Esta respuesta merece mucho más reconocimiento. Gracias derenard. – backdesk

+1

Use lambda: 'var sum = sampleArray.reduce ((e, i) => e + i)' – aloisdg