Foro de elhacker.net

Programación => Desarrollo Web => Mensaje iniciado por: geshiro en 25 Octubre 2015, 22:01 pm



Título: tabla dinamica en JS puro sin frameworks
Publicado por: geshiro en 25 Octubre 2015, 22:01 pm
como puedo hacer mi codigo hacerlo dinamico  , como lo hago mediante un solo for cada ves que le doy click se vayan agregando

Código
  1. <title>form</title>
  2. </head>
  3. <tr>
  4. <th>nombre:</th>
  5. <th>cantidad:</th>
  6. <th>precio:</th>
  7. </tr>
  8. <tr>
  9. <th><input type="text" id="name" placeholder="name"/></th>
  10. <th><input type="text" id="quantity" placeholder="quantity"/></th>
  11. <th><input type="text" id="price" placeholder="price"/></th>
  12. <th><input type="button" id="btn" value="add"/></th>
  13. </tr>
  14. </thead>
  15. <tbody id="data_table">
  16. </tbody>
  17. </table>
  18. <script type="text/javascript">
  19. window.onload = function(){
  20. byId('btn').onclick = function(){
  21. var data = {
  22. name: byId('name').value,
  23. quantity: byId('quantity').value,
  24. price: byId('price').value
  25. };
  26. for(i=0;i<byTag(document,'input').length;i++){
  27. document.getElementById("data_table").innerHTML += "<tr><td>"+data['name']+"</td><td>"+data['quantity']+"</td><td>"+data['price']+"</td></tr>";
  28. }
  29. console.log(arguments);
  30. }
  31. }
  32. </script>
  33. </body>
  34. </html>
  35.  


Título: Re: tabla dinamica en JS puro sin frameworks
Publicado por: eLank0 en 30 Octubre 2015, 13:57 pm
Buenas,

Tienes algunos errores de falta de atención o por copiar demasiado rápido, byId y byTag no son funciones nativas de javascript, entre otras cosas:

Este código funciona correctamente!

Código
  1. <html>
  2. <head>
  3. <title>form</title>
  4. </head>
  5. <body>
  6. <table>
  7. <thead>
  8. <tr>
  9. <th>nombre:</th>
  10. <th>cantidad:</th>
  11. <th>precio:</th>
  12. </tr>
  13. <tr>
  14. <th><input type="text" id="name" placeholder="name"/></th>
  15. <th><input type="text" id="quantity" placeholder="quantity"/></th>
  16. <th><input type="text" id="price" placeholder="price"/></th>
  17. <th><input type="button" id="btn" value="add" onClick="geshiro()"/></th>
  18. </tr>
  19. </thead>
  20. <tbody id="data_table">
  21. </tbody>
  22. </table>
  23. <script type="text/javascript">
  24. var geshiro = function(){
  25. var data = {
  26. name: document.getElementById('name').value,
  27. quantity: document.getElementById('quantity').value,
  28. price: document.getElementById('price').value
  29. };
  30.  
  31.  document.getElementById("data_table").innerHTML += "<tr><td>"+data['name']+"</td><td>"+data['quantity']+"</td><td>"+data['price']+"</td></tr>";
  32. }
  33. </script>
  34. </body>
  35. </html>

Salu2

PD: El for sobraba, ya que estabas añadiendo una fila para cada input de tu formulario, 3 text y un button.


Título: Re: tabla dinamica en JS puro sin frameworks
Publicado por: #!drvy en 30 Octubre 2015, 14:37 pm
Aparte de lo que ha mencionado eLank0, no te recomiendo usar innerHTML para tratar elementos del DOM. De hecho, no te lo recomiendo para nada que no sea modificar el DOM entero de una.

Cada vez que haces un innerHTML +=, el navegador re-procesa todo el dom y resetea todas las instancias y valores de los elementos afectados. Así, si por alguna casualidad tienes un checkbox en cada fila, seleccionas uno y añades otra fila, veras el que el checkbox seleccionado volverá a su estado original. Por no hablar que a pesar de que innerHTML esta implementado por todos los navegadores famosos, NO es un estándar.

Código
  1. window.onload = function(){
  2.    document.getElementById('btn').onclick = function(){
  3.  
  4.        var data = {
  5.            name: document.getElementById('name').value,
  6.            quantity: document.getElementById('quantity').value,
  7.            price: document.getElementById('price').value
  8.        };
  9.  
  10.        var tr = document.createElement('tr');
  11.  
  12.        for(var a=0; a < Object.keys(data).length; ++a){
  13.            var td = document.createElement('td');
  14.            td.textContent = data[Object.keys(data)[a]];
  15.            tr.appendChild(td);
  16.        }
  17.  
  18.        document.getElementById('data_table').appendChild(tr);
  19.    }
  20. }

PD: Ademas, innerHTML te puede provocar muchos dolores de cabeza cuando lo utilizas a cara del usuario... trata todo lo que le das como un código HTML, con sus respectivas posibilidades de meter XSS por ejemplo. Si vas insertar solo texto en algún lado, utiliza textContent.

Saludos


Título: Re: tabla dinamica en JS puro sin frameworks
Publicado por: MinusFour en 30 Octubre 2015, 15:36 pm
No veo porque trabajar con un objeto? Sería mejor un arreglo.
Código
  1. window.onload = function(){
  2.      document.getElementById('btn').addEventListener('click', function(){
  3. var data = [ document.getElementById('name'), document.getElementById('quantity'), document.getElementById('price') ];
  4.                var tr = data.reduce(function(tr, d){
  5.                     var td = document.createElement('td');
  6.                     td.textContent = d.value;
  7.                     tr.appendChild(td);
  8.                     return tr;
  9.                }, document.createElement('tr'));
  10.                document.getElementById('data_table').appendChild(tr);
  11. });
  12. }

Te ahorrarias cambiar tu función cada que agregues nuevos inputs con qSA (>IE 8+).

Código
  1. window.onload = function(){
  2.      document.getElementById('btn').addEventListener('click', function(){
  3. var data = document.querySelectorAll('input[type="text"]'); //una clase seria preferible
  4.                var tr = Array.prototype.reduce.call(data, function(tr, d){ //reduce >IE 9+
  5.                     var td = document.createElement('td');
  6.                     td.textContent = d.value;
  7.                     tr.appendChild(td);
  8.                     return tr;
  9.                }, document.createElement('tr'));
  10.                document.getElementById('data_table').appendChild(tr);
  11. });
  12. }