I am working on weather app in Vite + Typescript, no framework, just plain TS.
I want to have delete function for each weather list item. When I click on delete button clickedID gets passed down to delete function and that function deletes the item from savedWeatherList array, but I get this error.
(index):29 Uncaught ReferenceError: deleteItem is not defined
at HTMLButtonElement.onclick
I have this delete function in my main.ts file:
function deleteItem(clickedID: number): void {
console.log("Item with the id of: " + clickedID + " was clicked!");
savedWeatherList = savedWeatherList.filter((item) => {
return item.id !== clickedID;
});
}
In same main.ts file I add onclick attribute to the button where the function will be called.
const deleteButton: HTMLElement = document.createElement("button");
deleteButton.setAttribute("onclick", "deleteItem(item.id)");
Html attribute seems to be added correctly.
Why this function is not defined and can't be called?
My script tag in head section. Tried placing it in the body, but did not help.
<script crossorigin src="/src/main.ts" type="module"></script>
Use addEventListener instead of inline onclick Instead of setting the onclick attribute in the HTML, you can attach the event handler programmatically in your main.ts:
const deleteButton: HTMLElement = document.createElement("button");
deleteButton.textContent = "Delete";
deleteButton.addEventListener("click", () => deleteItem(item.id));