In the first place it is necessary to clarify that the way in which you add the row is incorrect, in fact you are only adding in the first place the tr
$('#tableStudents').append('<tr>');
What happens here is that JQuery automatically creates the ta and in turn closes the tag
and then adds td
after another and not within the tr
that is correct.
There are several ways to do this, you can build a String
of everything and do a append
direct to the table, or make append
to tr
before created with $('tr')
(example )
$('#tableStudents').append($('<tr>') //añadimos al tr
.append('<td>'+std.matricula +'</td>')
.... /* más filas */
); // cerramos el append a la tabla.
We also add a class that identifies the action of the button within the td
( .btncalificar
) to identify better when adding the Listener
<td><button type="button" class="btn btn-success btncalificar" >Calificar</button></td>
Using Event Delegate we add the Listener since they are dynamically added to dom
, this listener must be associated with an element that exists in the Sun, in this case the table with its id.
$('#tableStudents').on('click', '.btncalificar', function(event) { ...}
Example
$('.btn').click(function(event) {
for (var i = 0; i < 5; i++) {
$('#tableStudents').append($('<tr>')
// notese que no cerrramos el append , estamos
// añadiendo al tr
.append('<td> Matricula '+ i + '</td>')
.append('<td> Grupo '+ i + '</td>')
.append('<td> Materia '+ i + '</td>')
.append('<td> Unidad '+ i + '</td>')
.append('<td> Calificacion '+ i + '</td>')
.append('<td> <button type="button" class="btn btn-info btncalificar">Calificar</button></td>')
.append('</tr>')
);//cerramos el append a la tabla
}
});
$('#tableStudents').on('click', '.btncalificar', function(event) {
//Primera fila
console.log("Primera Fila : " + $(this).parents('tr').find('td:first-child').text());
//todos las columnas de la fila
console.log("Columnas de la Fila");
$.each($(this).parents('tr'), function(index, val) {
console.log($(val).text());
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn btn-primary">Agregar</button>
<table class="table table-bordered" id="tableStudents">
</table>