Foros del Web » Programando para Internet » Javascript »

Multiplicar valores de un arreglo en html dom

Estas en el tema de Multiplicar valores de un arreglo en html dom en el foro de Javascript en Foros del Web. Hola amigos... alguien podria ayudarme tengo un pekeño gran problema.. Tengo una tabla creada con js ya me inserta los datos en la base de ...
  #1 (permalink)  
Antiguo 27/06/2012, 11:40
Avatar de Ilidam  
Fecha de Ingreso: julio-2009
Ubicación: Veracruz
Mensajes: 108
Antigüedad: 14 años, 9 meses
Puntos: 0
Multiplicar valores de un arreglo en html dom

Hola amigos... alguien podria ayudarme tengo un pekeño gran problema..
Tengo una tabla creada con js ya me inserta los datos en la base de datos ahora lo k kiero....
primero a la ora de introducir la clave me jale el precio de ese producto de la tabla producto una vez echo eso introducir la cantidad y k me lo multiplike cantidad * precio y el resultado se muestre en total pero como es con arreglo no se como hacerlo se podra????

Código Javascript:
Ver original
  1. <?
  2.  
  3. $host = "localhost";
  4. $usuario1 = "root";
  5. $db = "gromero";
  6. $conexion=mysql_connect($host, $usuario1) or die("Error: " . mysql_error());
  7.  
  8.  mysql_select_db($db,$conexion);
  9. $qry =mysql_query("SELECT MAX(folio) AS folio FROM folio");
  10. if ($row = mysql_fetch_row($qry)) {
  11. $id = trim($row[0]);
  12. }
  13. $id2=$id+1;
  14.  
  15. $folio = 'A'.str_pad($id2,4,'0',STR_PAD_LEFT);
  16. echo $id;
  17. echo 'dato' + $qry;
  18.  
  19.  
  20. ?>
  21. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  22. <html xmlns="http://www.w3.org/1999/xhtml">
  23. <head>
  24. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  25. <title>Enviar Pedido...</title>
  26.  
  27. <style type="text/css">
  28. <!--
  29. html {  background-image: url(images/glowcolor.png); }
  30. #Layer3 {
  31.  
  32.         background-image: url(images/ddc.jpg);
  33.         background-position: center;
  34.     width:800px;
  35.  
  36.  
  37. }
  38. .Estilo16 {font-family: Arial, Helvetica, sans-serif}
  39. -->
  40.     </style>
  41.  
  42.  
  43. <script type="text/javascript">
  44. function alerta(){
  45. alert('desea imprimir')
  46. print();
  47. window.close();
  48.  
  49. }
  50. </script>
  51.  
  52. <script>
  53. var INPUT_NAME_PREFIX = 'inputName'; // this is being set via script
  54. var RADIO_NAME = 'totallyrad'; // this is being set via script
  55. var TABLE_NAME = 'tbl'; // this should be named in the HTML
  56. var ROW_BASE = 1; // first number (for display)
  57. var hasLoaded = false;
  58.  
  59. window.onload=fillInRows;
  60.  
  61. function fillInRows()
  62. {
  63.     hasLoaded = true;
  64.     addRowToTable();
  65.     addRowToTable();
  66. }
  67.  
  68. function sumar() {
  69. var n1 = document.tbl.cantidad["value"];
  70. var n2 = document.tbl.precio["value"];
  71. document.tbl.total["value"]=parseFloat(n1)*parseFloat(n2)
  72.  
  73. document.write("Longitud del array: " + miArray.length)
  74. for (i=0;i<miArray.length;i++){
  75.     document.write(miArray[i])
  76. }
  77. }
  78.  
  79.  
  80. function addRowToTable(num)
  81. {
  82.     if (hasLoaded) {
  83.         var tbl = document.getElementById(TABLE_NAME);
  84.         var nextRow = tbl.tBodies[0].rows.length;
  85.         var iteration = nextRow + ROW_BASE;
  86.                 if (num == null) {
  87.             num = nextRow;
  88.         } else {
  89.             num + ROW_BASE;
  90.         }
  91.  
  92.  
  93.         var row = tbl.tBodies[0].insertRow(num);
  94.  
  95.         row.className = 'classy' + (iteration % 2);
  96.  
  97.  
  98.  
  99.         var cell1 = row.insertCell(0);
  100.         var txtInp = document.createElement('input');
  101.         txtInp.setAttribute('type', 'text');
  102.         txtInp.setAttribute('name', "articulo[]");
  103.         txtInp.setAttribute('size', '43');
  104.         cell1.appendChild(txtInp);
  105.  
  106.                 var cell2 = row.insertCell(1);
  107.         var txtInp = document.createElement('input');
  108.         txtInp.setAttribute('type', 'text');
  109.         txtInp.setAttribute('name', "cantidad[]");
  110.         txtInp.setAttribute('size', '6');
  111.         cell2.appendChild(txtInp);
  112.  
  113.                 var cell3 = row.insertCell(2);
  114.         var txtInp = document.createElement('input');
  115.                 txtInp.type = 'text'; // 6
  116.                 txtInp.name = 'precio[]'; // 6
  117.                 txtInp.size = 7;
  118.                 txtInp.onkeyup = function(){addHiddenNeto(this.value)}
  119.                 txtInp.onfocus = function(){setHiddenNeto(this.value)}
  120.                 cell3.appendChild(txtInp);
  121.  
  122.                 var cell4 = row.insertCell(3);
  123.         var txtInp = document.createElement('input');
  124.         txtInp.setAttribute('type', 'text');
  125.         txtInp.setAttribute('name', "total[]");
  126.         txtInp.setAttribute('size', '5');
  127.                 txtInp.setAttribute("onFocus", 'sumar ()');
  128.         cell4.appendChild(txtInp);
  129.  
  130.  
  131.         var cell5 = row.insertCell(4);
  132.         var btnEl = document.createElement('input');
  133.         btnEl.setAttribute('type', 'image');
  134.         btnEl.setAttribute('src', 'images/borra.jpg');
  135.         btnEl.onclick = function () {deleteCurrentRow(this)};
  136.         cell5.appendChild(btnEl);
  137.  
  138.  
  139.         var cell6 = row.insertCell(5);
  140.         var btnadd = document.createElement('input');
  141.         btnadd.setAttribute('type', 'button');
  142.         btnadd.setAttribute('value', 'AGREGA');
  143.                 btnadd.setAttribute('onClick', 'addRowToTable ()');
  144.  
  145.         cell6.appendChild(btnadd);
  146.  
  147.         row.myRow = new myRowObject(txtInp);
  148.     }
  149. }
  150.  
  151.  
  152.  
  153. function deleteCurrentRow(obj)
  154. {
  155.     if (hasLoaded) {
  156.         var delRow = obj.parentNode.parentNode;
  157.         var tbl = delRow.parentNode.parentNode;
  158.         var rIndex = delRow.sectionRowIndex;
  159.         var rowArray = new Array(delRow);
  160.         deleteRows(rowArray);
  161.         reorderRows(tbl, rIndex);
  162.     }
  163. }
  164.  
  165.  
  166. function deleteRows(rowObjArray)
  167. {
  168.     if (hasLoaded) {
  169.         for (var i=0; i<rowObjArray.length; i++) {
  170.             var rIndex = rowObjArray[i].sectionRowIndex;
  171.             rowObjArray[i].parentNode.deleteRow(rIndex);
  172.         }
  173.     }
  174. }
  175.  
  176.  
  177. </script>
  178.  
  179. <style type="text/css">
  180. <!--
  181. #tbl td, th { padding: 0.5em; }
  182. .classy0 { background-color: #234567; color: #89abcd; }
  183. .classy1 { background-color: #89abcd; color: #234567; }
  184. -->
  185. </style>
  186.  
  187. <script type="text/javascript">
  188. function MostrarFecha()
  189.    {
  190.    var nombres_dias = new Array("Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado")
  191.    var nombres_meses = new Array("Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre")
  192.  
  193.    var fecha_actual = new Date()
  194.  
  195.    dia_mes = fecha_actual.getDate()
  196.    dia_semana = fecha_actual.getDay()
  197.    mes = fecha_actual.getMonth() + 1
  198.    anio = fecha_actual.getFullYear()
  199.  
  200.  
  201.    document.write( dia_mes + " de " + nombres_meses[mes - 1] + " de " + anio)
  202.    }
  203.  
  204. </script>
  205. </head>
  206.  
  207. <body>
  208.     <center>
  209.     <div id="Layer3">
  210.         <fieldset>
  211. <table style=' color:white '  align="center">
  212.  
  213.     <td  align="right"><a href="cerrarsesion.php"><font face="calibri" color="#FFFFFF">CERRAR SESION</font></a></td>
  214.   <tr>
  215.     <td><table>
  216.       <tr>
  217.         <td><div align="center">
  218.           <table style=' color:white ' width="40%" border="0" align="right">
  219.             <tr>
  220.                 <!-- Para que muestre la fecha -->
  221.                <font color="white"> <p align="right"> <strong> FECHA: </strong>
  222. <script language="JavaScript" type="text/javascript">
  223.  MostrarFecha();
  224. </script><p align="left" <td width="14%"> <strong> ADMIN:  </strong></td></p>
  225. </p> </font>
  226.  
  227.             </tr>
  228.  
  229.  
  230.           </table>
  231.         </div></td>
  232.       </tr>
  233.       <tr>
  234.         <td><form name="tbl" action="incompra.php" method="post">
  235.                 <strong><p align="center"><font color="white">DATOS DE COMPRA </font></p> </strong>
  236. <table style=' color:white '  id="tbl" align="center">
  237.  
  238.     <tr>
  239.     <td colspan="4"><p align="right">FOLIO:</p>   </td>
  240.          <td colspan="4"><label>
  241.       <input name="folio" type="text" id="folio" value="<?php echo $folio; ?>" readonly="readonly"/>
  242.     </label></td>
  243.   </tr>
  244.     <tr>
  245.     <td colspan="4"><p align="right">No. FACTURA:</p>   </td>
  246.          <td colspan="4"><label>
  247.       <input name="factura" type="text" onKeyUp="this.value = this.value.toUpperCase();"/>
  248.     </label></td>
  249.   </tr>
  250.     <tr>
  251.         <td>
  252.  <p align="center">
  253.      <label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  254.      <?php
  255.     $sql = "Select nombre from proveedor ";
  256.     $result = mysql_query( $sql);
  257. ?>
  258.          <font face="calibri" color="#FFFFFF"> PROVEEDOR </font> <select name="nombre"  tabindex="marca" style="width:290px">
  259.  
  260.     <option>-----------SELECCIONE PROVEEDOR-----------</option>
  261. <?php    while ( $row = mysql_fetch_array($result) ) {?>
  262.     <option style='text-transform: uppercase'> <?php echo $row[0];?>  </option>
  263.         <?php } ?>
  264. </select>
  265.       </label>
  266.     </p>
  267. </td>
  268.   </tr>
  269.  
  270.  
  271.  <tr>
  272.     <th>ARTICULO</th><th>CANTIDAD</th><th>PRECIO</th><th>TOTAL</th><th>BORRAR</th><th>AGREGAR</th>
  273.  
  274.   </tr>
  275.  
  276. </table>
  277.                 <br/>
  278.                 <center>
  279. <input type="image" src="images/continuar_id.gif"  type="submit" value="imprimir Factura" />
  280. </center>
  281.             </form></td>
  282.       </tr>
  283.     </table></td>
  284.   </tr>
  285.  
  286. </table>
  287.        </fieldset>
  288.  
  289.     </div></center>
  290. <br/>
  291.  
  292. </body>
  293. </html>

Última edición por Ilidam; 02/07/2012 a las 10:29
  #2 (permalink)  
Antiguo 26/07/2012, 09:00
 
Fecha de Ingreso: julio-2012
Ubicación: Medellin
Mensajes: 1
Antigüedad: 11 años, 9 meses
Puntos: 1
De acuerdo Respuesta: Multiplicar valores de un arreglo en html dom

hola este es el javascript que suma y multiplica los array

Código Javascript:
Ver original
  1. function sumacampos()
  2. {
  3.    //declaro variable que almacenara la suma total
  4.     var suma = 0;
  5.     //declaro variable que almacenara la multiplicacion total
  6.     var mult = 0;
  7.     var total=0;
  8.     //el "CampoaSumar" son los campos textBox que se sumaran
  9.     for(var i=0; i < document.tbl.CampoaSumar.length; i++)
  10.     {
  11.         //Comparo el id del campo en que me encuentro no lo sumo y sumar los demas
  12.         if(eval("document.getElementById('precio').id") != eval("document.tbl.CampoaSumar["+i+"].id") )
  13.             {
  14.  
  15.             //Recorro el vector de los campos y realizo la suma
  16.             suma = suma + parseFloat(eval("document.tbl.CampoaSumar["+i+"].value"));
  17.         }
  18.          
  19.     }
  20.          //Asigno la suma a un label que ira cambiando de acuerdo a la cantidad que se capture
  21.          document.getElementById('MiLabelTOTAL').innerHTML = suma;
  22.     for(var i=0; i< document.tbl.CampoaSumar.length; i++)
  23.     {
  24.     if(document.tbl.cantidad[i].value == ""){
  25.             this.document.tbl.cantidad[i].value = 0;
  26.         }
  27.         if(document.tbl.precio[i].value == ""){
  28.             this.document.tbl.precio[i].value = 0;
  29.         }
  30.         mult = parseFloat(eval("document.tbl.cantidad["+i+"].value")); //le asigno el valor de la cantidad
  31.             mult = mult * parseFloat(eval("document.tbl.precio["+i+"].value")); //hago la multiplicacion
  32.         document.tbl.total[i].value = mult; //llevo el total a al al input
  33.         total=total+mult;
  34.         this.document.getElementById('labelTOTAL').innerHTML = total;
  35.     }
  36.  
  37. }

debes de cambiar los nombres en estos tres asi
Código Javascript:
Ver original
  1. var cell2 = row.insertCell(1);
  2.             var txtInp = document.createElement('input');
  3.             txtInp.setAttribute('type', 'text');
  4.             txtInp.setAttribute('name', "CampoaSumar");
  5.         txtInp.setAttribute('id', 'cantidad');
  6.         txtInp.setAttribute('onblur', "sumacampos();");
  7.             txtInp.setAttribute('size', '6');
  8.             cell2.appendChild(txtInp);
  9.      
  10.                     var cell3 = row.insertCell(2);
  11.             var txtInp = document.createElement('input');
  12.                     txtInp.type = 'text'; // 6
  13.                     txtInp.name = 'CampoaSumar'; // 6
  14.             txtInp.setAttribute('id', 'precio');
  15.             txtInp.setAttribute('onblur', "sumacampos();");
  16.                     txtInp.size = 7;
  17.                     txtInp.onkeyup = function(){addHiddenNeto(this.value)}
  18.                     txtInp.onfocus = function(){setHiddenNeto(this.value)}
  19.                     cell3.appendChild(txtInp);
  20.      
  21.                     var cell4 = row.insertCell(3);
  22.             var txtInp = document.createElement('input');
  23.             txtInp.setAttribute('type', 'text');
  24.             txtInp.setAttribute('name', "total");
  25.         txtInp.setAttribute('id', "total");
  26.             txtInp.setAttribute('size', '5');
  27.             cell4.appendChild(txtInp);

y en la tabla colocas algo como esto de abajo y te queda funcionando como tu lo quieres lo que pasa es que no te va a cargar desde el primer items sino desde el segundo estoy mirando como solucionarlo por que no me da espero y te sirva de algo jejeje te lo iba a dejar todo pero dice que es muy largo para colocarlo soy nuevo en este foro....es que se vio interesante hacerlo

Código HTML:
Ver original
  1. <tr>
  2.         <th>ARTICULO</th><th>CANTIDAD</th><th>PRECIO</th><th>TOTAL</th><th>BORRAR</th><th>AGREGAR</th>
  3.      
  4.       </tr>
  5.      
  6.     </table>
  7. <table style=' color:blue ' id="tbl1" align="center">
  8. <tr>
  9. <th>Total Cantidad: <label id="MiLabelTOTAL" >0</label></th>
  10. <td><th>Total: <label id="labelTOTAL" >0</label></th></td>
  11. </tr>
  12. <tr>
  13. </tr>
  #3 (permalink)  
Antiguo 23/08/2012, 10:02
Avatar de Ilidam  
Fecha de Ingreso: julio-2009
Ubicación: Veracruz
Mensajes: 108
Antigüedad: 14 años, 9 meses
Puntos: 0
Respuesta: Multiplicar valores de un arreglo en html dom

Hola arthurhdez91 muchas gracias por la respuesta aunque no lo habia checado esta muy bien...puede resolver el proble y me esta funcionando perfectamente aunke le echare un vistazo a tu codigo = y se puede hacer muchas cosas mas con esto y pues si es muy interesente este tema saludos...

Etiquetas: dom, html, input, js, multiplicar, php, select, arreglos
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 08:17.