1

This event listener wont fire, have I built it correctly?

I am trying to add the event listener when each new line is added after being fetched from the database.

const renderEmployee = (element) =>{

let newRow =
`
<tr>
    <td>${element.lastName}</td>
    <td>${element.firstName}</td>
    <td>${element.email}</td>
    <td>${element.department}</td>
    <td>${element.location}</td>
    <td>
        <button data-empid="${element.id}" id="${element.id}Del"><i class="fa fa-trash" aria-hidden="true"></i></button>
        <button data-empid="${element.id}" id="${element.id}Edit"><i class="fas fa-edit"></i></button>
    </td>
</tr>

`
document.getElementById("employeeData").innerHTML += newRow;

// set event listeners for delete and edit 
$(`#${element.id}Del`).click(() => deleteEmployee($(`#${element.id}Del`).attr("data-empid")));
$(`#${element.id}Del`).click(() => console.log("test"));

}

  • A better approach is to apply the event handler to the table and let events from the buttons propagate up to it. That way you don't have to worry about adding listeners on each new row. Since you're using jquery: $('myTable tbody').on('click', '.btn-del', function(){}); Add the 'btn-del' class to your button simply to help with selection and do the same for the edit button. Then you can use $(this) inside the callback function to get the element that triggered the event (the button). – Phaelax z Oct 08 '21 at 15:04

0 Answers0