Ver Mensaje Individual
  #6 (permalink)  
Antiguo 02/02/2014, 11:04
Avatar de djaevi
djaevi
 
Fecha de Ingreso: marzo-2007
Ubicación: Moreno, Buenos Aires
Mensajes: 400
Antigüedad: 17 años, 1 mes
Puntos: 47
Respuesta: Añadir/Eliminar filas de tablas html con javascript, gran problema

Aca te lo dejo corregido con la opcion de agregar onfocus a cada campo input y un boton que borra las filas de la tabla y otro que las agrega.

Código HTML:
Ver original
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  4. <title> Tablas Dinamicas</title>
  5.  
  6. <script type="text/javascript">


Código Javascript:
Ver original
  1. function agregar_fila() {
  2.  
  3.     var tabla = document.getElementById("factura");
  4.    
  5.     var fila = tabla.insertRow();
  6.    
  7.     var celda1 = fila.insertCell(0);
  8.     var celda2 = fila.insertCell(1);
  9.     var celda3 = fila.insertCell(2);
  10.     var celda4 = fila.insertCell(3);
  11.    
  12.     var campo1 = document.createElement("input");
  13.         campo1.type = "text";
  14.         campo1.setAttribute("onclick","vaciar_campo(this);");
  15.        
  16.     var campo2 = campo1.cloneNode(true);
  17.     var campo3 = campo1.cloneNode(true);
  18.    
  19.     var campo4 = document.createElement("input");
  20.         campo4.type = "button";
  21.         campo4.value = "Borrar Fila";
  22.         campo4.onclick = function() {
  23.        
  24.             var fila = this.parentNode.parentNode;
  25.             var tbody = tabla.getElementsByTagName("tbody")[0];
  26.            
  27.             tbody.removeChild(fila);
  28.            
  29.         }
  30.    
  31.     celda1.appendChild(campo1);
  32.     celda2.appendChild(campo2);
  33.     celda3.appendChild(campo3);
  34.     celda4.appendChild(campo4);
  35.  
  36. }
  37.  
  38. function vaciar_campo(input) {
  39.    
  40.     input.value = "";
  41.    
  42. }


Código HTML:
Ver original
  1.     td {
  2.        
  3.         width:160px;
  4.            
  5.     }
  6. </head>
  7.  
  8.  
  9. <table id="factura" cellpadding="5" cellspacing="5" border="1">
  10.  
  11.     <tr>
  12.         <td>Cantidad</td>
  13.         <td>Descripcion</td>
  14.         <td>Precio</td>
  15.         <td>
  16. <input type="button" value="Agregar Fila" onclick="agregar_fila();"></td>
  17.     </tr>
  18.  
  19.  
  20. </body>
  21. </html>

Notese que añadi los eventos onfocus usando setAttribute porque si uso onfocus = {...} o addEventListener al clonar el input, el input clonado pierde dicho registro de eventos.

Saludos

Última edición por djaevi; 02/02/2014 a las 11:21