Tengo un código jQuery donde puedo eliminar la fila de la tabla dentro de <tbody> . Y ahora, creé un código JavaScript donde puedo hacer lo mismo cuando agrego una fila de tabla. Aquí está mi código para la referencia:
<script> let newRowContent = '<tr id="tableRow">'; newRowContent += '<td>'; newRowContent += '<div class="form-group">'; newRowContent += '<select class="form-control" name="book">'; newRowContent += '@foreach( $books as $row )'; newRowContent += '<option value="{{ $row->id}}">{{ $row->title}}</option>'; newRowContent += '@endforeach'; newRowContent += '</select>'; newRowContent += '</div>'; newRowContent += '</td>'; newRowContent += '<td>'; newRowContent += '<div class="form-group">'; newRowContent += '<input type="number" class="form-control form-control-sm" placeholder="Qty">'; newRowContent += '</div>'; newRowContent += '</td>'; newRowContent += '<td>'; newRowContent += '<button id="removeTableRow" type="button" class="btn btn-sm btn-outline-danger">'; // This one right here is not working. newRowContent += '<span data-feather="trash"></span>'; newRowContent += '</button>'; newRowContent += '</td>'; newRowContent += '</tr>'; $('#addTableRow').click(function() { $(newRowContent).appendTo($('#books-detail-table')); feather.replace(); }); $('#removeTableRow').click(function() { $('#tableRow').remove(); }) </script>¿Cómo puedo hacer funcionar el botón dentro de la etiqueta de JavaScript? ¿Cómo puedo lograr en el trabajo de este código? Cualquier ayuda será apreciada. Muchas gracias.
Debería agregar un controlador de clics al botón removeTableRow en el momento en que se agrega al DOM:
$('#addTableRow').click(function() { $(newRowContent).appendTo($('#books-detail-table')); feather.replace(); $('#removeTableRow').click(function() { $('#tableRow').remove(); }) }); Sin embargo, todavía tiene el problema de que cada vez que agrega una fila de la tabla, está agregando un <tr id="tableRow"> que da como resultado varias etiquetas con la misma ID. (También está duplicando <button id="removeTableRow"> ). Esto no es válido y debe resolverse antes de que pueda funcionar.
Aquí está la respuesta.
$('#addTableRow').click(function() { $(newRowContent).appendTo($('#books-detail-table')); document.getElementById('removeTableRow').addEventListener("click", function() { $('#tableRow').remove(); }) feather.replace(); });