Ver Mensaje Individual
  #3 (permalink)  
Antiguo 02/07/2014, 14:32
Avatar de Briss
Briss
 
Fecha de Ingreso: junio-2011
Mensajes: 1.293
Antigüedad: 12 años, 10 meses
Puntos: 12
Respuesta: Suma mismo input (array)

Cita:
Iniciado por ocp001a Ver Mensaje
Si tienes esos inputs dentro de un form, es fácil recorrerlo.

Código HTML:
Ver original
  1. <form name="productos">
  2.     <input type="text" name="aporte[]" value="10" />
  3.     <input type="text" name="aporte[]" value="20" />
  4.     <input type="text" name="aporte[]" value="30" />
  5.     <input type="button" value="sumar" onclick="suma(this.form)" />
  6.     <input type="text" name="total" id="total" value="" />
  7. </form>

Código Javascript:
Ver original
  1. suma=function(f){
  2.     var total=0;
  3.     for(var x=0;x<f.length;x++){//recorremos los campos dentro del form
  4.         if(f[x].name.indexOf('aporte')!=-1){//si el nombre campo contiene la palabra 'aporte'
  5.             total+=Number(f[x].value);//sumamos, convirtiendo el contenido del campo a número
  6.         }
  7.     }
  8.     document.getElementById('total').value=total;//al final colocamos la suma en algún input.
  9. }
Gracias ocp001a funciona perfecto... entiendo que verifica el nombre para sumar.... no me queda muy claro esto suma=function(f) ... f es un elemento de aporte???? bueno es como si tuviera aporte' + i ?????
gracias nuevamente