Skip to content
Advertisement

Getting the correct ID to delete in site with multiple posts

I just ran into an issue I just can’t get my head around.

I have a site with all the applications a user has made, looking like this: dashboard

I have a button to delete/cancel on each post this exact post (Bewerbung zurückziehen).

When pressing that button, a modal opens with some text. When he presses the delete button in the modal the application is canceled if the user is sure to delete it.

However, it is always the first on the page that gets deleted, not the one on which the button was pressed.

I have to somehow get the application’s ID on which the button was pressed, but I have zero clue on how to do it.

Here is the blade code:

JavaScript

This is the JS code for the modal:

JavaScript

Advertisement

Answer

This is your form :

JavaScript

but it’s in a loop, so presumably you are creating lots of them, each with the same button with the same ID :

JavaScript

Since ID has to be unique, when your javascript fires, it looks for the element with ID “ok_btn” to submit the relevant form. Since there are lots (again, ID should be unique) then it just submits the first one it comes to. So it will always just delete the first one on the page.

My suggestion would be :

  1. Don’t put the form or the modal in the loop.
  2. Put the modal at the end, with the form inside it, and within the form have a hidden field (called, say, “delete_id”.
  3. Use javascript to populate the “delete_id” with the relevant ID of the thing to be deleted when the user clicks to bring up the modal.
  4. Use the confirmation button to submit the form, as you do at the moment.
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement