How to make the delete button work in ejs


I am not sure what is wrong with my code. I am new to express.
app.js list.ejs

I thought I misspelled a variable, but I am unsure what I did wrong. I am making a todo list project using express and node.js and I need to have a remove task option.

My app.js code is:'/removetask', (req, res) => {
  const task = req.body.task;
  task.splice(task.indexOf(task), 1);

and my list.js used in the browser is:

<form action="/" method="post">
  <input type="text" name="newItem" >
  <button type="submit">Add</button>
  <button formaction="/removetask" type="submit" id="top">Remove</button>


The primary issue is that you’re trying to use the splice method on a variable named task, which seems to be a string (as it’s coming from the form’s input field).

But you need to maintain an array of tasks to add and remove task

const tasks = [] //array of tasks'/removetask', (req, res) => {
  const taskIndex = tasks.indexOf(req.body.task);
  if (taskIndex !== -1) {
    tasks.splice(taskIndex, 1);

With these changes, you will maintain an array of tasks on the server-side and correctly add or remove tasks.
The splice method is used to modify the tasks array.

Answered By – Alif Haider

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published