Delete a record in indexdb from a button in a dynamically created row

I have a table with rows which gets added dynamicaly to the DOM from a row inside template tags. In the row i have a delete button which deletes the row from the table and should also delete the entry from the IndexDB. The method to delete the entry gets called from the onclick eventlistner of the delete button. The request.onsuccess from the IndexDB triggers but the database entry is not disappearing.

The same method called from the console to delete the entry with the same key is successful. Same if i call the method from a button which is not added to the DOM afterwards. So i assume the problem lays in this method which creates the table rows from a template. I already realized that i need to get the td elements again after i import the node to be able to attach event listeners.

/**
 * Create the visual element of the task object and its properties and append it to the
 * task table
 * 
 * @param {*} task the task data object
 */
function addTaskToTaskList(task) {

    let taskTableBody = document.querySelector('#task-table tbody');
    // get the task template
    let taskTemplateItem = document.querySelector("#task-table thead template").content;
    let tableCells = taskTemplateItem.querySelectorAll('td');
    // fill the cells with the data from the task object
    tableCells[0].innerHTML = task.tID;
    tableCells[1].innerHTML = task.title;
    tableCells[2].innerHTML = task.startDate;
    tableCells[3].innerHTML = task.endDate;
    tableCells[4].innerHTML = task.priority;
    // create a copy of the node to insert it later
    let node = document.importNode(taskTemplateItem, true);
    let tableCellsDOM = node.querySelectorAll('td');
    
    // add eventlisteners for action buttons
    let actionBtns = tableCellsDOM[5].querySelectorAll('button');
    actionBtns[1].addEventListener('click', function (event) {
        let rowClicked = this.parentNode.parentNode;
        let taskID = rowClicked.querySelector('#task-id').innerHTML;
        console.log(taskID);
        Database.deleteItemInObjectStore("Tasks", taskID);
        removeTaskFromTable(rowClicked.rowIndex);
    });

    // add the task node to the table
    taskTableBody.appendChild(node);
}

The method call Database.deleteItemInObjectStore("Tasks", taskID); is correct and triggers the request.onsucces from the IndexDB objectstore, also from the button in the row i created. But the entry is not deleted from the IndexDB.

Sample rendered table:

rendered table

No frameworks allowed.

112 thoughts on “Delete a record in indexdb from a button in a dynamically created row”

Leave a Comment