I made a delete function for a table; it works but when the page is refreshed the items return. The project can be found on codepen here
const showExpenses = () => {
const table = document.getElementById('expenseTable');
table.innerHTML = '';
for(let i = 0; i < expenses.length; i++){
expenseTable.innerHTML += `
<tr >
<td class="expItem">${expenses[i].name}</td>
<td class="expItem">${expenses[i].date}</td>
<td class="expItem">$${expenses[i].amount}</td>
<td><a class="deleteButton" href="#" data-id="${expenses[i].id}">Delete</a></td>
</tr>
`;
}
}
//Remove buttom
$(document).ready(function() {
$('body').on('click', '.deleteButton', function(e) {
e.preventDefault(); // prevent the href default
// if you need to access the id...
let deleteID = $(this).data('id');
$(this).closest('tr').remove();
})
})
To achieve this, the idea here is to save it to a type of storage that is persistent across a page reload. You can achieve this with localStorage as well as sessionStorage. In my example, I'll just show you how you can use localStorage, but you can read more about Session Storage here (https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage).
In your $(document).ready(...) is where you can load from local storage storage, and in your deleteButton onClick listener, you can save to storage. Local Storage uses key-value pairs to store and retrieve data, so whatever you call it when you save the data is also how you retrieve it:
$(document).ready(function() {
// As soon as jquery loads, load from storage
// it will return null if nothing is stored yet
deletedExpenses = localStorage.getItem("deletedExpenses");
$('body').on('click', '.deleteButton', function(e) {
e.preventDefault(); // prevent the href default
// if you need to access the id...
let deleteID = $(this).data('id');
$(this).closest('tr').remove();
// You first have to load from storage the array of deleted items,
var deletedArr = localStorage.getItem("deletedExpenses");
// If you have nothing stored, this will return null,
// And if that's the case, create new array
if (!deletedArr)
deletedArr = [];
}
// then push to this array another ID that got deleted
deletedArr.push(deleteID);
localStorage.setItem("deletedExpenses", deletedArr);
})
})
Obviously this is not a complete example but it should lead you in the right direction.
Learn more about localStorage here: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage