Foros del Web » Programando para Internet » Javascript »

[SOLUCIONADO] Añadir/Eliminar filas de tablas html con javascript, gran problema

Estas en el tema de Añadir/Eliminar filas de tablas html con javascript, gran problema en el foro de Javascript en Foros del Web. Hola gente, buenos días, soy de echo muy nuevo en lo que se refiere al tema de javascript y html, para ser mas conciso hace ...
  #1 (permalink)  
Antiguo 01/02/2014, 07:43
 
Fecha de Ingreso: febrero-2014
Mensajes: 32
Antigüedad: 10 años, 2 meses
Puntos: 0
Añadir/Eliminar filas de tablas html con javascript, gran problema

Hola gente, buenos días, soy de echo muy nuevo en lo que se refiere al tema de javascript y html, para ser mas conciso hace 4 días que estoy intentando aprender ambos lenguajes, pero mi ambición con el poder de estos dos supera mi conocimiento, entonces que mas poder hacer que recurrir a la ayuda de alguno de ustedes, cabe decir que mi problema lo busque y vi varios temas similares en el foro pero nada que me pueda ayudar, sin mas que decir al problema...

Tengo este codigo

Código:
<!DOCTYPE html>
<html>
<body>

<table id="myTable" border="1">
<tr>

</tr>
</table><br>

<button onclick="myCreateFunction()">Crear</button>
<button onclick="myDeleteFunction()">Borrar</button>

<script>
function myCreateFunction()
{
var table = document.getElementById("myTable");
  {
  var row = table.insertRow(0);
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
  cell1.innerHTML = "Quiero insertar input text aaqui";
  cell2.innerHTML = "Aqui tambien";
  }
}
function myDeleteFunction()
{
document.getElementById("myTable").deleteRow(0);
}
</script>

</body>
</html>

El código funciona bien cumpliendo su propósito, el problema va en que yo lo quiero para otro, quiero insertar en la tabla, es decir, en las celdas (Si es asi como se le dice) campos de textos, no que quede solo un texto como ahora sucede, también quiero redimensionar el tamaño de las celdas...

Agradecería que alguien me eche una mano :)
  #2 (permalink)  
Antiguo 01/02/2014, 08:08
Colaborador
 
Fecha de Ingreso: septiembre-2013
Ubicación: España
Mensajes: 3.648
Antigüedad: 10 años, 7 meses
Puntos: 578
Respuesta: Añadir/Eliminar filas de tablas html con javascript, gran problema

Con innerHTML puedes insertar el contenido mediante texto:

Código:
cell1.innerHTML = '<input type="text">';
Y para redimensionar usa las propiedades de CSS:

Código:
cell1.style.height="20px";
cell1.style.width="100px";
Puedes poner los píxels que quieras...

  #3 (permalink)  
Antiguo 01/02/2014, 12:02
 
Fecha de Ingreso: febrero-2014
Mensajes: 32
Antigüedad: 10 años, 2 meses
Puntos: 0
Respuesta: Añadir/Eliminar filas de tablas html con javascript, gran problema

Muchas gracias PHPeros, Tema solucionado :D
  #4 (permalink)  
Antiguo 01/02/2014, 19:05
Avatar de 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

Tambien podes usar DOM y crear los elementos dinamicamente: x ejemplo.

Código Javascript:
Ver original
  1. function myCreateFunction() {
  2.  
  3. var table = document.getElementById("myTable");
  4.     var row = table.insertRow(0);
  5.     var cell1 = row.insertCell(0);
  6.     var cell2 = row.insertCell(1);
  7.  
  8. // CREO UN ELEMENTO DEL TIPO INPUT CON document.createElement("NOMBRE TAG HTML QUE QUIERO CREAR");
  9.  
  10.     var input = document.createElement("input");
  11.         input.type = "text";
  12.         input.className = "myInput";
  13.         input.style.height = "20px";
  14.         input.style.width = "100px";
  15.  
  16. // HAGO UN CLON DEL PRIMER INPUT PARA TENER OTRO IGUAL
  17.    
  18.     var input2 = input.cloneNode(true);
  19.    
  20. // CON EL METODO appendChild(); LOS AGREGO A LA CELDA QUE QUIERO
  21.  
  22.     cell1.appendChild(input);  
  23.     cell2.appendChild(input2);
  24.  
  25. }

En muchos casos cuando modificas, creas o borras muchas cosas del arbol html con javascript, usar DOM te clarifica mucho mas el codigo, y lei por ahi que es mas estandar utilizar DOM que innerHTML. Igualmente en mi experiencia personal cuando también usé innerHTML nunca tuve problemas nisiquiera con I.E.

Saludos
  #5 (permalink)  
Antiguo 02/02/2014, 01:13
 
Fecha de Ingreso: febrero-2014
Mensajes: 32
Antigüedad: 10 años, 2 meses
Puntos: 0
Respuesta: Añadir/Eliminar filas de tablas html con javascript, gran problema

Hola djaevi, gracias por tu codigo, estuve metiendole mano y funciona realmente, pero no fue mi solucion ya que al input queria agregarle un onFocus y desde las propiedades donde se creaba el input es decir
Código:
var input = document.createElement("input");
        input.type = "text";
        input.className = "urlresp";
        input.value = "Usuario";
        input.style.height = "20px";
        input.style.width = "100px";
ahi no supe como agregarselo, reitero, se poco y nada de javascript, pero a continuacion voy a dejar el primer codigo correjido por PHPeros que funciona, tu codigo y el ultimo que use como aporte para que alguien que tenga un problema igual o similar al mio pueda usar estos codes, ahi van...

Este es el primer codigo corregido por PHPeros

Código HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    <script>
        function myCreateFunction() {
            var table = document.getElementById("myTable"); {
                var row = table.insertRow(0);
                var cell1 = row.insertCell(0);
                var cell2 = row.insertCell(1);
                cell1.innerHTML = '<input type="text">';
                cell2.innerHTML = '<input type="text" id=txt>';
                cell1.style.height = "20px";
                cell1.style.width = "100px";
                cell2.style.height = "20px";
                cell2.style.width = "30px";
                txt.style.width = "30px";
            }
        }

        function myDeleteFunction() {
            document.getElementById("myTable").deleteRow(0);
        }
    </script>
</head>

<body>
    <button onclick="myCreateFunction()" type="button">
        <img src="Boton.png">
    </button>
    <button onclick="myDeleteFunction()" type="button">
        <img src="Boton2.png">
    </button>
    <p>&nbsp;</p>
    <table id="myTable" border="0">
        <tr>
            <td style="height: 20px; width: 100px;">
                <input name="urlresp" type="text" id="urlresp" onfocus="this.value=''" value="Url respuesta">
            </td>
            <td style="height: 20px; width: 30px;">
                <input name="ptss" type="text" id="txt" style="width: 30px;" onfocus="this.value=''" value="0">
            </td>
        </tr>
    </table>
</body>

</html> 

Este codigo es el que proporciono djaevi, lo modifique un poco acuerdo a mis necesidades

Código HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Agregar y quitar celdas</title>
    <script>

        function myCreateFunction() {

            var table = document.getElementById("myTable");
            var row = table.insertRow(0);
            var cell1 = row.insertCell(0);
            var cell2 = row.insertCell(1);
            // CREO UN ELEMENTO DEL TIPO INPUT CON document.createElement("NOMBRE TAG HTML QUE QUIERO CREAR");



            var input = document.createElement("input");
            input.type = "text";
            input.className = "urlresp";
            input.value = "Usuario";
            input.style.height = "20px";
            input.style.width = "100px";

            // Creo un segundo elemento Input


            var input2 = document.createElement("input");
            input2.type = "text";
            input2.className = "ptss";
            input2.value = "0";
            input2.autofocus;
            input2.style.height = "20px";
            input2.style.width = "30px";


            // CON EL METODO appendChild(); LOS AGREGO A LA CELDA QUE QUIERO
            cell1.appendChild(input);
            cell2.appendChild(input2);

            document.getElementById("input2").onFocus();

        }



        function myDeleteFunction() {
            document.getElementById("myTable").deleteRow(0);
        }
    </script>
</head>

<body>
    <table id="myTable" border="0">
        <tr>

        </tr>
    </table>

    <button onclick="myCreateFunction()" type="button">Crear</button>
    <button onclick="myDeleteFunction()" type="button">Borrar</button>
</body>

</html> 
Este otro es el ultimo que realmente me sirvio ya que pude agregarle el evento onFocus, pero no supe agregarle un boton para eliminar las celdas, pero da igual no importa.

Código HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Agregar y quitar celdas</title>
    <script>
        function vaciar(control) {
            control.value = '';
        }

        function verificarEntrada(control) {
            if (control.value == '')
                alert('Debe ingresar datos');
        }


        var orden = 1;

        function clonarNodos() {
            var id = document.getElementById("myTable");
            var nuevos = id.cloneNode(true);
            nuevos.style.id = 'enlaces' + orden;
            orden++;
            id = document.getElementById("NewTable");
            id.appendChild(nuevos);
        }

        function myDeleteFunction() {
            document.getElementById("myTable").deleteRow(0);
        }
    </script>
</head>

<body>
    <table id="myTable" border="0">
        <tbody>
            <tr>
                <td>
                    <input value="Usuario" style="height: 20px; width: 100px;" id="urlresp" type="text" onFocus="vaciar(this)">
                    <input value="0" style="height: 20px; width: 30px;" class="ptss" type="text" onFocus="vaciar(this)">
                    </br>
                </td>
        </tbody>
    </table>

    <table id="NewTable" border="0">
    </table>
    <button onclick="javascript:clonarNodos()" value="Clonar nodos">Crear</button>
</body>

</html> 
  #6 (permalink)  
Antiguo 02/02/2014, 11:04
Avatar de 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
  #7 (permalink)  
Antiguo 03/02/2014, 04:08
 
Fecha de Ingreso: febrero-2014
Mensajes: 32
Antigüedad: 10 años, 2 meses
Puntos: 0
Respuesta: Añadir/Eliminar filas de tablas html con javascript, gran problema

Gracias de nuevo djaevi por tus codigos, combinando el primero que me diste mas este otro ultimo di con el codigo final que en verdad era lo que queria y seria el seguiente :)

Código HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Agregar y quitar celdas</title>
    <script> 
Código Javascript:
Ver original
  1. function myCreateFunction() {
  2.  
  3.             var table = document.getElementById("myTable");
  4.             var row = table.insertRow(0);
  5.             var fila = table.insertRow();
  6.             var cell1 = row.insertCell(0);
  7.             var cell2 = row.insertCell(1);
  8.             // CREO UN ELEMENTO DEL TIPO INPUT CON document.createElement("NOMBRE TAG HTML QUE QUIERO CREAR");
  9.  
  10.  
  11.  
  12.             var input = document.createElement("input");
  13.             input.type = "text";
  14.             input.className = "urlresp";
  15.             input.value = "Url respuesta";
  16.             input.setAttribute("onclick", "vaciar_campo(this);");
  17.             input.style.height = "20px";
  18.             input.style.width = "100px";
  19.  
  20.             // Creo un segundo elemento Input
  21.  
  22.  
  23.             var input2 = document.createElement("input");
  24.             input2.type = "text";
  25.             input2.className = "ptss";
  26.             input2.value = "0";
  27.             input2.setAttribute("onclick", "vaciar_campo(this);");
  28.             input2.style.height = "20px";
  29.             input2.style.width = "30px";
  30.  
  31.  
  32.             var campo4 = document.createElement("input");
  33.             campo4.type = "button";
  34.             campo4.value = "-";
  35.             campo4.onclick = function ()
  36.  
  37.             {
  38.  
  39.                 var fila = this.parentNode.parentNode;
  40.                 var tbody = table.getElementsByTagName("tbody")[0];
  41.  
  42.                 tbody.removeChild(fila);
  43.  
  44.             }
  45.  
  46.  
  47.             // CON EL METODO appendChild(); LOS AGREGO A LA CELDA QUE QUIERO
  48.             cell1.appendChild(input);
  49.             cell2.appendChild(input2);
  50.             cell2.appendChild(campo4);
  51.         }
  52.  
  53.  
  54.  
  55.         function vaciar_campo(input) {
  56.  
  57.             input.value = "";
  58.  
  59.         }

Código HTML:
Ver original
  1. </head>
  2.  
  3.     <button onclick="myCreateFunction()" type="button">
  4.         <img src="Boton1.png">
  5.     </button>
  6.     <br>
  7.     <table id="myTable" border="0">
  8.         <tr>
  9.             <input name="urlresp" type="text" id="urlresp" style="height: 20px; width: 100px;" onFocus="vaciar_campo(this)" value="Url respuesta">
  10.             <input name="ptss" type="text" class="ptss" id="ptss" style="height: 20px; width: 30px;" onFocus="vaciar_campo(this)" value="0">
  11.         </tr>
  12.     </table>
  13.  
  14.  
  15. </body>
  16.  
  17. </html>


Gracias de nuevo .
Saludos

Etiquetas: filas, funcion, html, input, tablas
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 16:46.