-1

I have a jQuery code where I can remove the table row inside <tbody>. And now, I created a JavaScript code where I can do the same when I add table row. Here's my code for the reference:

<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>

How can I function the button inside JavaScript tag? How can I achieve in working this code? Any help will be appreciated. Thanks so much.

jhenryj09
  • 45
  • 8

2 Answers2

0

You would have to add a click handler to the removeTableRow button at the time it is added to the DOM:

$('#addTableRow').click(function() {
    $(newRowContent).appendTo($('#books-detail-table'));
    feather.replace();

    $('#removeTableRow').click(function() {
        $('#tableRow').remove();
    })
});

However, you still have the problem that every time you add a table row, you are adding a <tr id="tableRow"> which results in multiple tags with the same ID. (You are also duplicating <button id="removeTableRow">.) This is invalid, and needs to be resolved before this can be made functional.

kmoser
  • 8,780
  • 3
  • 24
  • 40
0

Here is the answer.

$('#addTableRow').click(function() {
    $(newRowContent).appendTo($('#books-detail-table'));
    document.getElementById('removeTableRow').addEventListener("click", function() {
        $('#tableRow').remove();
    })
    feather.replace();
});
needman9
  • 96
  • 5