Reputation: 2896
I'm trying to make a delete alert using sweetalert
but whenever I confirm the delete
from the sweetalert, first row of the table gets deleted always. Even if I try to delete, for example, the 3rd row from the table, sweetalert will delete the first row.
How can I correct my code?
<tbody>
@foreach($album_names as $album)
<tr>
<td>{{ $album->album_name }}</td>
<td>
{!! Form::open(['route' => ['album.destroy',$album->id], 'method' => 'delete','id'=>'delete_form']) !!}
<button class="btn btn-danger" id="delete">Delete</button>
<script type="text/javascript">
$('button#delete').on('click', function(e){
e.preventDefault();
swal({
title : "Are you sure?",
text : "You will not be able to recover this Album!",
type : "warning",
showCancelButton : true,
confirmButtonColor: "#DD6B55",
confirmButtonText : "Yes, delete it!",
cancelButtonText : "No, Cancel delete!",
closeOnConfirm : false,
closeOnCancel : false
},
function(isConfirm){
if(isConfirm){
swal("Deleted!","your album has been deleted", "success");
setTimeout(function() {
$("#delete_form").submit();
}, 2000); // 1 second delay
}
else{
swal("cancelled","Your album is safe", "error");
}
}
);});
</script>
{!! Form::close() !!}
</td>
</tr>
@endforeach
</tbody>
Upvotes: 0
Views: 2216
Reputation: 11951
The problem is that you're generating all of this within a loop. Each delete button has an ID of "#delete" and each form has an ID of "#delete_form", but there are many buttons and forms, each with the same ID.
You aren't scoping your selector to know which form to actually submit. Switch your IDs to classes, and make sure to select the form based on which button was clicked.
As an example, your code can be changed to something like this:
@foreach($album_names as $album)
<tr>
<td>{{ $album->album_name }}</td>
<td>
{!! Form::open(['route' => ['album.destroy',$album->id], 'method' => 'delete','class'=>'delete_form']) !!}
<button class="btn btn-danger delete-btn">Delete</button>
{!! Form::close() !!}
</td>
</tr>
@endforeach
<script type="text/javascript">
$('button.delete-btn').on('click', function(e){
e.preventDefault();
var self = $(this);
swal({
title : "Are you sure?",
text : "You will not be able to recover this Album!",
type : "warning",
showCancelButton : true,
confirmButtonColor: "#DD6B55",
confirmButtonText : "Yes, delete it!",
cancelButtonText : "No, Cancel delete!",
closeOnConfirm : false,
closeOnCancel : false
},
function(isConfirm){
if(isConfirm){
swal("Deleted!","your album has been deleted", "success");
setTimeout(function() {
self.parents(".delete_form").submit();
}, 2000); //2 second delay (2000 milliseconds = 2 seconds)
}
else{
swal("cancelled","Your album is safe", "error");
}
});
});
</script>
This is untested, but it should help get you started. Let me know if this helps.
Upvotes: 4