Home > OS >  Laravel: Confirmation deletion does not work
Laravel: Confirmation deletion does not work

Time:07-29

I'm having a problem with deleting confirmation; specifically, when I click on the delete button, the item is deleted directly without the window for confirming the deletion appearing first.

Can someone help me?

function confirmDelete(){
    let deleteLink = document.querySelector('.delete');

    deleteLink.addEventListener('click', function(event) {
        event.preventDefault();

        let choice = confirm(this.getAttribute('data-confirm'));

        if (choice) {
            window.location.href = this.getAttribute('action');
        }
    });
}
                    <form action="{{ route('client.destroy',compact('client'))}}" method="POST">

                        <a  href="{{route('client.edit', compact('client'))}}">Edit</a>

                        @csrf
                        @method('DELETE')

                        <button type="submit"  onclick="confirmDelete()" data-confirm="Sure?">Delete</button>
                    </form>

CodePudding user response:

Here is the solution.

Set button type button and set id to form.

<form action="{{ route('client.destroy',compact('client'))}}" method="POST" id="form_id">

  <a  href="{{route('client.edit',compact('client'))}}">Edit</a>

@csrf
@method('DELETE')

  <button type="button"  onclick="confirmDelete()" data-confirm="Sure?">Delete</button>
</form>

Some change in your function.

function confirmDelete() {
  let deleteLink = document.querySelector('.delete');

  deleteLink.addEventListener('click', function (event) {
    event.preventDefault();

    let choice = confirm($(this).data('confirm'));

    if (choice) {
      $('#form_id').submit();
      // window.location.href = this.getAttribute('action');
    }
  });
}

If you do this for multiple client make sure FORM ID is unique.

CodePudding user response:

Your should prevent default behaviour(which is submitting form onclick) of input:

onclick="event.preventDefault();confirmDelete()"
  • Related