0

de que manera puedo sumar el total de los input dinámicos que genero al darle clic en agregar productos, con los input que están en mi table, pues se suman por separados. Es decir en el campo Total suma los input que están en agregar productos, pero al intentar multiplicar los inputs que están en mi table, deja de sumar los que están en agregar productos. Esto cuando el value esta sin miles y decimales.

Al colocarle los miles y decimales me arroja en Total NaN

EN ESTE FRAGMENTO ESTA SIN LOS MILES

<!DOCTYPE html>
<html lang="es_ES">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <script type="text/javascript">

   var nextinput = 0;
   function AgregarCampos() {
       nextinput++;
       campo = '<li id="idLi' + nextinput + '">' +

'<select id="txt' + nextinput + '" step="any"' +
' oninput="multiplicar(\'txt' + nextinput + '\',\'nmb' + nextinput + '\',\'acumu' + nextinput + '\',\'prinact' + nextinput + '\');" >' +

'<option value="REFRESCO 2L HIT-NARANJA [ COCACOLA RIF J123456789 ] Precio: 1500.00">REFRESCO 2L HIT-NARANJA [ COCACOLA RIF J123456789 ] Precio: 1500.00</option>' +
'<option value="REFRESCO 2L GOLDEN-NARANJA [ PEPSICOLA DE COCA ] Precio: 1200.00">REFRESCO 2L GOLDEN-NARANJA [ PEPSICOLA DE COCA ] Precio: 1200.00</option>' +
'<option value="REFRESCO 2L NARANJA-ORANGE Precio: 1000.00">REFRESCO 2L NARANJA-ORANGE Precio: 1000.00</option>   ' +
'</select>' +

'<input type="text" size="15" id="prinact' + nextinput + '" step="any" ' +
' oninput="multiplicar(\'txt' + nextinput + '\',\'nmb' + nextinput + '\',\'acumu' + nextinput + '\',\'prinact' + nextinput + '\',\'preciou' + nextinput + '\');" />' +

'<input type="text" size="15" id="preciou' + nextinput + '" step="any" ' +
' oninput="multiplicar(\'txt' + nextinput + '\',\'nmb' + nextinput + '\',\'acumu' + nextinput + '\',\'prinact' + nextinput + '\',\'preciou' + nextinput + '\');" />' +

'<input type="number" size="15" id="nmb' + nextinput + '" step="any" ' +
' oninput="multiplicar(\'txt' + nextinput + '\',\'nmb' + nextinput + '\',\'acumu' + nextinput + '\',\'prinact' + nextinput + '\',\'preciou' + nextinput + '\');" />' +

'<input type="text" size="15"   id="acumu' + nextinput + '" step="any" class="monto total"' +
' oninput="multiplicar(\'txt' + nextinput + '\',\'nmb' + nextinput + '\',\'acumu' + nextinput + '\',\'prinact' + nextinput + '\',\'preciou' + nextinput + '\');" />' +

'</li>';

        $("#campos").append(campo);
       
        }
   function multiplicar(txt, nmb, acumu, prinact, preciou) {
       var m1 = document.getElementById(txt).value;
       var m2 = document.getElementById(nmb).value;

       //EXP.REG PARA EXTRAER LO QUE ESTA EN CORCHETES
       var PrinActi = /\[([\w\s]*)\]/g;
       if (PrinActi.test(m1)) 
       {
           var PrinAct2 = m1.match(PrinActi)[0]; 
           var PrinAct3 = PrinAct2.replace(/[\[\]]/g, '');
           document.getElementById(prinact).value = PrinAct3;
       }

       //EXP.REG PARA EXTRAER LO QUE ESTA DESPUES DE PRECIO
       var PriceU = /precio: (\d+)/i;
       if (PriceU.test(m1)) 
       {
           var PriceU2 = m1.match(PriceU); 
           var PriceU3 = parseInt(PriceU2[1]); 
           document.getElementById(preciou).value = PriceU3; 
       }
       
       var P = /precio: (\d+)/i;
       var matchA = m1.match(P);
       var Price = parseInt(matchA[1]);
       r = Price * m2;
       document.getElementById(acumu).value = r;

       //SUMA EL TOTAL DE LOS INPUT QUE TENGA LA CLASS .monto 
       var total = 0;
       $(".monto").each(function () {
           if (isNaN(parseFloat($(this).val()))) {
               total += 0;
           } else {
               total += parseFloat($(this).val());
           }
       });
       document.getElementById('T').value = total;
   }
    </script>
</head>
<body>
    <form id="form" name="form" method="post">
         <div align="left">
    <a href="#" onclick="AgregarCampos();">Agregar Producto</a>
    <ul id="campos"></ul>
        
       <table id="tblPosicionesNueva">
            <thead>
                <tr>
                    <th></th>
                    <th></th>
                    <th></th>
                    <th></th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
           <tr>
                <td>
                     &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
                    <input type="text"  id="inputBusqueda" style="width:495px" value="REFRESCO"  />
                </td>
                <td>
                    <input type="text"  style="width:130px" value"COLA"/>
                </td>
                <td>
                    <input type="text" class="mult" value="2500" style="width:130px"/>
                </td> 
                <td>
                    <input type="number" class="mult" value="5" style="width:165px"/>
                </td> 
                <td>
                    <input type="text" class="total" value="12500" style="width:130px"/>
                </td>
          </tr>
          <tr>
                <td>
                    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
                    <input type="text"  id="" style="width:495px" value="REFRESCO"  />
                </td>
                <td>
                    <input type="text"  style="width:130px" value"COLA"/>
                </td>
                <td>
                    <input type="text" class="mult" value="1500" style="width:130px"/>
                </td> 
                <td>
                    <input type="number" class="mult" value="4" style="width:165px"/>
                </td> 
                <td>
                    <input type="text" class="total" value="6000" style="width:130px"/>
                </td>
          </tr>
       </tbody>
    </table>

             <br />
             <tr>
                <td>
                    Total
                </td>
                <td>
                    <input type="text" id="T" value="0" disabled>
                </td>
            </tr>
    </div>
    </form>
</body>
</html>

<script>
    // GENEREA EVENTO click y keyup PARA LOS ELEMENTOS INPUT CON CLASE .mult
    var input = document.querySelectorAll(".mult");
input.forEach(function(e) {
    e.addEventListener("click",multiplica);
    e.addEventListener("keyup",multiplica);
});
    // FUNCION PARA MULTIPLICAR RECORRIENDO LOS tr QUE TIENEN LA CLASE .mult INDICANDO EL TOTAL
function multiplica() {
    var tr = this.closest("tr");
    var total = 1;
    var inputs = tr.querySelectorAll(".mult");
    inputs.forEach(function (e) {
        total *= e.value;
    });
    tr.querySelector(".total").value = total;
    calcularTotal(this.closest("table"));
}
    // FUNCION QUE CALCULA LA SUMA OBTIENE LOS TOTALES Y LOS SUMA
function calcularTotal(e) {
    var total=0;
    var totales=e.querySelectorAll(".total");
    totales.forEach(function(e) {
        total+=parseFloat(e.value);
    });
    document.getElementById('T').value = new Intl.NumberFormat('de-DE').format(total) + ",00";
}
</script>

EN ESTE FRAGMENTO ESTA CON LOS MILES

<!DOCTYPE html>
<html lang="es_ES">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <script type="text/javascript">

   var nextinput = 0;
   function AgregarCampos() {
       nextinput++;
       campo = '<li id="idLi' + nextinput + '">' +

'<select id="txt' + nextinput + '" step="any"' +
' oninput="multiplicar(\'txt' + nextinput + '\',\'nmb' + nextinput + '\',\'acumu' + nextinput + '\',\'prinact' + nextinput + '\');" >' +

'<option value="REFRESCO 2L HIT-NARANJA [ COCACOLA RIF J123456789 ] Precio: 1.500.000,00">REFRESCO 2L HIT-NARANJA [ COCACOLA RIF J123456789 ] Precio: 1.500.000,00</option>' +
'<option value="REFRESCO 2L GOLDEN-NARANJA [ PEPSICOLA DE COCA ] Precio: 1.200.500,00">REFRESCO 2L GOLDEN-NARANJA [ PEPSICOLA DE COCA ]] Precio: 1.200.500,00</option>' +
'<option value="REFRESCO 2L NARANJA-ORANGE Precio: 1.000.100,00">REFRESCO 2L NARANJA-ORANGE  Precio: 1.000.100,00</option>   ' +
'</select>' +

'<input type="text" size="15" id="prinact' + nextinput + '" step="any" ' +
' oninput="multiplicar(\'txt' + nextinput + '\',\'nmb' + nextinput + '\',\'acumu' + nextinput + '\',\'prinact' + nextinput + '\',\'preciou' + nextinput + '\');" />' +

'<input type="text" size="15" id="preciou' + nextinput + '" step="any" ' +
' oninput="multiplicar(\'txt' + nextinput + '\',\'nmb' + nextinput + '\',\'acumu' + nextinput + '\',\'prinact' + nextinput + '\',\'preciou' + nextinput + '\');" />' +

'<input type="number" size="15" id="nmb' + nextinput + '" step="any" ' +
' oninput="multiplicar(\'txt' + nextinput + '\',\'nmb' + nextinput + '\',\'acumu' + nextinput + '\',\'prinact' + nextinput + '\',\'preciou' + nextinput + '\');" />' +

'<input type="text" size="15"   id="acumu' + nextinput + '" step="any" class="monto total"' +
' oninput="multiplicar(\'txt' + nextinput + '\',\'nmb' + nextinput + '\',\'acumu' + nextinput + '\',\'prinact' + nextinput + '\',\'preciou' + nextinput + '\');" />' +

'</li>';

        $("#campos").append(campo);
       
        }
   function multiplicar(txt, nmb, acumu, prinact, preciou) {
       var m1 = document.getElementById(txt).value;
       var m2 = document.getElementById(nmb).value;

       //EXP.REG PARA EXTRAER LO QUE ESTA EN CORCHETES
       var PrinActi = /\[([\w\s]*)\]/g;
       if (PrinActi.test(m1)) 
       {
           var PrinAct2 = m1.match(PrinActi)[0]; 
           var PrinAct3 = PrinAct2.replace(/[\[\]]/g, '');
           document.getElementById(prinact).value = PrinAct3;
       }

       //EXP.REG PARA EXTRAER LO QUE ESTA DESPUES DE PRECIO
       var PriceU = /precio: (\d+)/i;
       if (PriceU.test(m1)) 
       {
           var PriceU2 = m1.match(PriceU); 
           var PriceU3 = parseInt(PriceU2[1]); 
           document.getElementById(preciou).value = PriceU3; 
       }
       
       var P = /precio: (\d+)/i;
       var matchA = m1.match(P);
       var Price = parseInt(matchA[1]);
       r = Price * m2;
       document.getElementById(acumu).value = r;

       //SUMA EL TOTAL DE LOS INPUT QUE TENGA LA CLASS .monto 
       var total = 0;
       $(".monto").each(function () {
           if (isNaN(parseFloat($(this).val()))) {
               total += 0;
           } else {
               total += parseFloat($(this).val());
           }
       });
       document.getElementById('T').value = total;
   }
    </script>
</head>
<body>
    <form id="form" name="form" method="post">
         <div align="left">
    <a href="#" onclick="AgregarCampos();">Agregar Producto</a>
    <ul id="campos"></ul>
        
       <table id="tblPosicionesNueva">
            <thead>
                <tr>
                    <th></th>
                    <th></th>
                    <th></th>
                    <th></th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
           <tr>
                <td>
                     &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
                    <input type="text"  id="inputBusqueda" style="width:495px" value="REFRESCO"  />
                </td>
                <td>
                    <input type="text"  style="width:130px" value"COLA"/>
                </td>
                <td>
                    <input type="text" class="mult" value="12.500.000,00" style="width:130px"/>
                </td> 
                <td>
                    <input type="number" class="mult" value="5" style="width:165px"/>
                </td> 
                <td>
                    <input type="text" class="total" value="12.500.000,00" style="width:130px"/>
                </td>
          </tr>
          <tr>
                <td>
                    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
                    <input type="text"  id="" style="width:495px" value="REFRESCO"  />
                </td>
                <td>
                    <input type="text"  style="width:130px" value"COLA"/>
                </td>
                <td>
                    <input type="text" class="mult"  value="6.000.000,00" style="width:130px"/>
                </td> 
                <td>
                    <input type="number" class="mult" value="4" style="width:165px"/>
                </td> 
                <td>
                    <input type="text" class="total"  value="6.000.000,00" style="width:130px"/>
                </td>
          </tr>
       </tbody>
    </table>

             <br />
             <tr>
                <td>
                    Total
                </td>
                <td>
                    <input type="text" id="T" value="0" disabled>
                </td>
            </tr>
    </div>
    </form>
</body>
</html>

<script>
    // GENEREA EVENTO click y keyup PARA LOS ELEMENTOS INPUT CON CLASE .mult
    var input = document.querySelectorAll(".mult");
input.forEach(function(e) {
    e.addEventListener("click",multiplica);
    e.addEventListener("keyup",multiplica);
});
    // FUNCION PARA MULTIPLICAR RECORRIENDO LOS tr QUE TIENEN LA CLASE .mult INDICANDO EL TOTAL
function multiplica() {
    var tr = this.closest("tr");
    var total = 1;
    var inputs = tr.querySelectorAll(".mult");
    inputs.forEach(function (e) {
        total *= e.value;
    });
    tr.querySelector(".total").value = total;
    calcularTotal(this.closest("table"));
}
    // FUNCION QUE CALCULA LA SUMA OBTIENE LOS TOTALES Y LOS SUMA
function calcularTotal(e) {
    var total=0;
    var totales=e.querySelectorAll(".total");
    totales.forEach(function(e) {
        total+=parseFloat(e.value);
    });
    document.getElementById('T').value = new Intl.NumberFormat('de-DE').format(total) + ",00";
}
</script>

De que manera puedo multiplicar y sumar con miles y decimales y que los input dinamico y los de mi table se sumen juntos

4
  • Podrías compartir el html? Así te ayudaríamos mejor. el 8 jun. 2021 a las 21:28
  • @JeanGotopo, el html esta en amboas fragmento de código en la parte de abajo amigo el 8 jun. 2021 a las 22:11
  • Ese es un html creado con la función. Donde lo estás insertando? el 8 jun. 2021 a las 22:20
  • @JeanGotopo correcto con la función agregar campos el va añadiéndome los input dinámicos, y están los otros que son los input de mi table., Intentaejecutar el codigo para que veas el 8 jun. 2021 a las 22:28

1 respuesta 1

0

Te sale NaN (Not a Number) porque en el value, lo está considerando los miles como un string dado que colocas varios puntos como separadores de miles, y el código al verlo así lo toma como un string y por ello no puede multiplicar un número con un string. Además agunos values los tenías sin el igual, más que todo los que eran igual a "COLA". Te facilito la parte del código que tenia el problema con la propuesta de solución:

        <tr>
            <td>
                 &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
                <input type="text"  id="inputBusqueda" style="width:495px" value="REFRESCO"  />
            </td>
            <td>
                <input type="text"  style="width:130px" value="COLA"/>
            </td>
            <td>
                <input type="text" class="mult" value="12500000" style="width:130px"/>
            </td> 
            <td>
                <input type="number" class="mult" value="5" style="width:165px"/>
            </td> 
            <td>
                <input type="text" class="total" value="12500000" style="width:130px"/>
            </td>
      </tr>
      <tr>
            <td>
                &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
                <input type="text"  id="" style="width:495px" value="REFRESCO"  />
            </td>
            <td>
                <input type="text"  style="width:130px" value="COLA"/>
            </td>
            <td>
                <input type="text" class="mult"  value="6000000" style="width:130px"/>
            </td> 
            <td>
                <input type="number" class="mult" value="4" style="width:165px"/>
            </td> 
            <td>
                <input type="text" class="total"  value="6000000" style="width:130px"/>
            </td>
      </tr>
10
  • Amigo, yo coloque 2 fragmento de código uno donde no coloco los miles y otro donde si coloco los miles, donde coloco los miles me sale el error de NaN, quiero saber como multiplicar sin quitarle los miles, adicional a eso que los totales de los input dinámicos y los totales que están en mi table se sumen juntos, ya que lo hacen por separado, te invito a que ejecutes los 2 fragmento de código para que comprendas el problema que tengo. Otra cosa los value que dicen COLAno los estoy multiplicando, si ves el código multiplico y sumo los que tienen la class "mult" y "total" de los input de mi table el 8 jun. 2021 a las 23:36
  • Ya corrí el código antes de hacer la respuesta, comprende que te sale error NaN, porque estas usando separadores de miles, y el lenguaje no toma los puntos como separadores de miles. Corre el que te digo para que veas que no te pone error NaN. Si lo que quieres es mostrar con los puntos, te sugiero que lo hagas con una función para tratar el resultado convertirlo en string y luego colocarle los puntos. el 8 jun. 2021 a las 23:45
  • No deberías valorar una respuesta como negativa, si implica un esfuerzo considerando que tu código es largo, y debiste probarlo, aun así valore tu pregunta como positiva. el 8 jun. 2021 a las 23:46
  • Pero es que la respuesta que me ofreciste es la misa que coloque en mi primer fragmento de código, ejecútela para que veas que si funciona, el problema es que si empiezo a multiplicar los input dinámicos no suma esos totales con los totales de mi input que están en mi table el 9 jun. 2021 a las 0:10
  • quizás no me explico bien lo que quiero hacer, o cual es mi problema como tal. el 9 jun. 2021 a las 0:12

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.