1

I have a programme using .js and ejs that when you enter a weight it creates a row with your weight and date and posts to the website

I need a way to delete the row that when that row's delete button is clicked. To delete the row I am trying to get the index value of that row. Then I can use that value with Mongoose to remove that entry but I can't seem to figure out how to pass the value to my app.js. Below in the EJS snippet of code.

I thought about using map function but doesn't seem appropriate as I just want the index value of a row.

<form action="/delete" method="post">
      <%  weightData.forEach(function(entry, index) { %>

            <tr>
        <th scope="col"><%= entry.date %> </th>
        <th scope="col"><%= entry.weight %></th>
        <th scope="col"><%= entry.change %> lbs</th>
      <th> <button type="submit"><i class="fas fa-trash-alt"></i></button> </th>
  </tr>

          <% }) %>
</form>

How can I get it so that when the delete button is clicked I can access the index value on my app.js page? Or is there a simply more obvious way that I'm missing? Thanks!

slih01
  • 21
  • 2

2 Answers2

1

You can pass the id of your entry by adding an hidden input to your form.

<input type="hidden" name="id" value="<%= entry.id %>">

Since you have many entries, you will want a separate form for each entry.

Alternatively, you can handle the request without forms.

Define a JavaScript function deleteEntry that gets the entry id as input and performs an AJAX request to /delete using, for example, the fetch API. Then call this function passing the id on the onClick event of your button.

I'd prefer this second option as it gives you more flexibility. You won't have to reload the page and you can remove the entry row with JavaScript (see remove) once your request has been completed successfully.

1

You need to add the onClick event in your button like this:

<th> <button type="submit" onClick="handleDelete(index)"}><i class="fas fa-trash-alt"></i></button> </th>

now when the button is clicked the handleDelete function will be called with the index as argument.

const handleDelete = (index) => {
   //you can now access the index here..
}