简体   繁体   中英

Laravel: Confirmation deletion does not work

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 class="btn btn-primary" href="{{route('client.edit', compact('client'))}}">Edit</a> @csrf @method('DELETE') <button type="submit" class="btn btn-danger delete" onclick="confirmDelete()" data-confirm="Sure?">Delete</button> </form>

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 class="btn btn-primary" href="{{route('client.edit',compact('client'))}}">Edit</a>

@csrf
@method('DELETE')

  <button type="button" class="btn btn-danger delete" 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM