2012-06-01 39 views
52

Estoy tratando de agregar filas al tbody de una tabla. Pero estoy teniendo problemas para lograr eso. En primer lugar, se llama a la función donde todo tiene lugar el cambio de un menú desplegable de una página html. Creé una cadena tr que contenía todo el td que contenía los elementos html, texto y otras cosas. Pero cuando estoy tratando de añadir esa fila generada a la mesa usando:Agregar filas a tbody de una tabla usando jQuery

$(newRowContent).appendTo("#tblEntAttributes tbody"); 

me encuentro con un error. El nombre de la tabla es tblEntAttributes y estoy intentando agregarlo al tbody.

En realidad, lo que está sucediendo es que jQuery no puede obtener tblEntAttributes como un elemento html. Pero puedo acceder usando documemt.getElementById("tblEntAttributes");

¿Hay alguna manera de que pueda lograr esto agregando filas al tbody de la tabla? Tal vez un bypass o algo así.

Aquí está el código completo:

var newRowContent = "<tr><td><input type=\"checkbox\" id=\"" + chkboxId + "\" value=\"" + chkboxValue + "\"></td><td>" + displayName + "</td><td>" + logicalName + "</td><td>" + dataType + "</td><td><input type=\"checkbox\" id=\"chkAllPrimaryAttrs\" name=\"chkAllPrimaryAttrs\" value=\"chkAllPrimaryAttrs\"></td><td><input type=\"checkbox\" id=\"chkAllPrimaryAttrs\" name=\"chkAllPrimaryAttrs\" value=\"chkAllPrimaryAttrs\"></td></tr>"; 

$("#tblEntAttributes tbody").append(newRowContent); 

Una cosa que me olvidé de mencionar es la función donde el código está escrito es en realidad la función de devolución de llamada para el éxito de una llamada AJAX. Puedo acceder a la tabla usando document.getElementById("tblEntAttributes") pero por alguna razón $(#tblEntAttributes) no parece funcionar.

+0

Se puede publicar algún fragmento de su DOM (en su mayoría la tabla en cuestión) –

+1

$ ('# Tabla1> tbody') Tomado de http://stackoverflow.com/questions/6763006/how-to-get- the-tbody-element-of-a-table-using-jquery/6763036 # 6763036 –

Respuesta

9

nunca he encontrado un problema tan extraño como esto! o.O

¿Sabes cuál era el problema? $ no está funcionando. Probé el mismo código con jQuery como jQuery("#tblEntAttributes tbody").append(newRowContent); y funciona como un encanto!

¡No hay idea de por qué ocurre este extraño problema!

+7

Debe leer sobre jQuery. no conflicto(). Podría ser que estés usando otras bibliotecas que también usan $ alias http://api.jquery.com/jQuery.noConflict/ –

61

("#tblEntAttributes tbody")

necesidades sean

($("#tblEntAttributes tbody")).

No se selecciona el elemento con la sintaxis correcta

He aquí un ejemplo de ambos

$(newRowContent).appendTo($("#tblEntAttributes")); 

y

$("#tblEntAttributes tbody").append(newRowContent); 

trabajo http://jsfiddle.net/xW4NZ/

+5

Invertir la sintaxis puede ser más legible: '$ (" # tblEntAttributes tbody "). append (newRowContent);'. –

+1

@Wirey, eso no funciona. – Anupam

+1

@ Frédéric Hamidi: No funciona tan bien. – Anupam

2

Como @wirey dijo appendTo sho ULD trabajo, si no, entonces usted puede probar esto:

$("#tblEntAttributes tbody").append(newRowContent); 
2

Aquí es una versión appendTo usando el desplegable html que usted ha mencionado. Inserta otra fila en "cambio".

$('#dropdown').on('change', function(e) { 
    $('#table').append('<tr><td>COL1</td><td>COL2</td></tr>'); 
}); 

Con un ejemplo para que juegue. ¡La mejor de las suertes!

http://jsfiddle.net/xtHaF/12/

30

uso de este

$("#tblEntAttributes tbody").append(newRowContent); 
0

Con Lodash puede crear una plantilla y usted puede hacer eso siguiente manera:

<div class="container"> 
     <div class="row justify-content-center"> 
      <div class="col-12"> 
       <table id="tblEntAttributes" class="table"> 
        <tbody> 
         <tr> 
          <td> 
           chkboxId 
          </td> 
          <td> 
           chkboxValue 
          </td> 
          <td> 
           displayName 
          </td> 
          <td> 
           logicalName 
          </td> 
          <td> 
           dataType 
          </td> 
         </tr> 
        </tbody> 
       </table> 
       <button class="btn btn-primary" id="test">appendTo</button> 
      </div> 
     </div> 
    </div> 

Y aquí va la javascript:

 var count = 1; 
     window.addEventListener('load', function() { 
      var compiledRow = _.template("<tr><td><input type=\"checkbox\" id=\"<%= chkboxId %>\" value=\"<%= chkboxValue %>\"></td><td><%= displayName %></td><td><%= logicalName %></td><td><%= dataType %></td><td><input type=\"checkbox\" id=\"chkAllPrimaryAttrs\" name=\"chkAllPrimaryAttrs\" value=\"chkAllPrimaryAttrs\"></td><td><input type=\"checkbox\" id=\"chkAllPrimaryAttrs\" name=\"chkAllPrimaryAttrs\" value=\"chkAllPrimaryAttrs\"></td></tr>"); 
      document.getElementById('test').addEventListener('click', function (e) { 
       var ajaxData = { 'chkboxId': 'chkboxId-' + count, 'chkboxValue': 'chkboxValue-' + count, 'displayName': 'displayName-' + count, 'logicalName': 'logicalName-' + count, 'dataType': 'dataType-' + count }; 
       var tableRowData = compiledRow(ajaxData); 
       $("#tblEntAttributes tbody").append(tableRowData); 
       count++; 
      }); 
     }); 

Aquí está en jsbin

Cuestiones relacionadas