Ver Mensaje Individual
  #2 (permalink)  
Antiguo 27/01/2010, 02:58
quimfv
Colaborador
 
Fecha de Ingreso: marzo-2008
Ubicación: Sabadell
Mensajes: 4.897
Antigüedad: 16 años, 1 mes
Puntos: 574
Respuesta: Sumar dos campos tipo array y devolver valor a campo array

Creo que os complicáis la vida.... pero bueno ahí va una solucion posible, obviamente he tenido que simular los inputs generados dinamicamente....

Quim


Código Javascript:
Ver original
  1. function calcula(){
  2. var vcantidad=document.getElementsByName('cantidad[]');
  3. var vprecio_u=document.getElementsByName('precio_unitario[]');
  4. var unidades=0;
  5. var totaltotal=0;
  6. i=0;
  7. for (var obj in document.getElementsByName('total_p[]')){
  8.  if (i<document.getElementsByName('cantidad[]').length){
  9.   document.getElementsByName('total_p[]')[i].value=parseFloat(vcantidad[i].value)*parseFloat(vprecio_u[i].value);
  10.   unidades+=parseFloat(vcantidad[i].value);
  11.   totaltotal+=parseFloat(vcantidad[i].value)*parseFloat(vprecio_u[i].value);
  12.   }
  13.   i++;
  14.   }
  15.   document.getElementById("unidades").innerHTML=unidades;
  16.   document.getElementById("totaltotal").innerHTML=totaltotal;
  17. }

Código HTML:
Ver original
  1. <table width="50%" border="1" cellspacing="0" cellpadding="0">
  2.   <tr>
  3.     <td align='center'>Cantidad</td>
  4.     <td align='center'>Precio unitario</td>
  5.     <td align='center'>Total parcial</td>
  6.   </tr>
  7.   <tr>
  8.     <td width="58" align='center'><input  type='text' size='4' name='cantidad[]' value="" ></td>
  9.     <td align='center'  width="58"><input  type='text' size='4'  name='precio_unitario[]' value=""></td>
  10.     <td align='center' width="56"><input  type='text' size='4' name='total_p[]' value="" ></td>
  11.   </tr>
  12.   <tr>
  13.     <td width="58" align='center'><input  type='text' size='4' name='cantidad[]'  value=""></td>
  14.     <td align='center'  width="58"><input  type='text' size='4'  name='precio_unitario[]' value=""></td>
  15.     <td align='center' width="56"><input  type='text' size='4' name='total_p[]' value="" ></td>
  16.   </tr>
  17.   <tr>
  18.     <td width="58" align='center'><input  type='text' size='4' name='cantidad[]'  value=""></td>
  19.     <td align='center'  width="58"><input  type='text' size='4'  name='precio_unitario[]' value=""></td>
  20.     <td align='center' width="56"><input  type='text' size='4' name='total_p[]' value="" ></td>
  21.   </tr>
  22.   <tr>
  23.     <td width="58" align='center' id="unidades">&nbsp;</td>
  24.     <td align='center'  width="58">Total</td>
  25.     <td align='center' width="56" id="totaltotal">&nbsp;</td>
  26.   </tr>
  27. <input name="botfes" type="button" id="botfes" value="Fes" onClick="calcula()">

(Incluso funciona con IE6!!!!)

Deberías evitar los posibles NaN si hay campos sin valor...

Última edición por quimfv; 27/01/2010 a las 03:08