my javascript knowledge is also very poor so please help. I'm trying to secure the users page and add confirm dialog to delete. But I don't know how to catch the submit methods. I use confirm from sweetalert2, but unfortunately the form method runs without clicking on any of the buttons.
So my question is how to modify the code?
<form action="{{ route('users.destroy', ['user' => \Illuminate\Support\Facades\Auth::id()]) }}" method="post">
@csrf
@method('DELETE')
<button id="comfirm-delete" class="btn btn-danger">User Delete</button>
</form>
<script>
$(function () {
'use strict';
var comfirmDelete = $('#comfirm-delete');
if (comfirmDelete.length) {
comfirmDelete.on('click', function() {
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
showCancelButton: true,
confirmButtonText: 'Yes, delete it!',
cancelButtonText: 'No, cancel!',
customClass: {
confirmButton: 'btn btn-primary',
cancelButton: 'btn btn-outline-danger ml-1'
},
buttonsStyling: false
}).then(function(result) {
if (result.value) {
Swal.fire({
icon: 'success',
title: 'Deleted!',
text: '',
customClass: {
confirmButton: 'btn btn-success'
}
});
}
});
});
}
});
</script>
Here is how
If you have more than one form, you need a class and to cache the form instead of using $('#myForm')
$(function() {
const $myForm = $('#myForm')
.on('submit', function(e) {
e.preventDefault();
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
showCancelButton: true,
confirmButtonText: 'Yes, delete it!',
cancelButtonText: 'No, cancel!',
customClass: {
confirmButton: 'btn btn-primary',
cancelButton: 'btn btn-outline-danger ml-1'
},
buttonsStyling: false
}).then(function(result) {
if (result.value) {
Swal.fire({
icon: 'success',
title: 'Deleted!',
text: '',
customClass: {
confirmButton: 'btn btn-success'
}
});
setTimeout(function() {
$myForm[0].submit()
}, 2000); // submit the DOM form
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@10.15.5/dist/sweetalert2.all.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/sweetalert2@9.17.2/dist/sweetalert2.min.css" rel="stylesheet" />
<form id="myForm">
<button class="confirm-delete btn btn-danger">User Delete</button>
</form>