I’m trying to make a delete confirmation with Twitter bootsrap in a foreach loop. My code works, but every time, it deletes the first record in the table(the id passing is not working correctly). Could you please help.
Here is my code
<table class="table">
<thead>
<th>#</th>
<th>Name</th>
<th>Email</th>
<th>Position</th>
<th></th>
</thead>
<tbody>
@foreach ($employees as $key => $employee)
<!-- twitter bootstrap delete confrimation -->
<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="deleteModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="deleteModal">Confirm Remove</h4>
</div>
<div class="modal-body">
<p>You are about to remove a team member.</p>
<p>Do you want to proceed?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal"><i class="fa fa-btn fa-times"></i>Cancel</button>
{!! Form::open(['route' => ['employees.destroy', $employee->id], 'method' => 'DELETE', 'style' => 'display: inline-block']) !!}
<button type="submit" class="btn btn-danger btn-ok"><i class="fa fa-btn fa-trash-o"></i>Remove</button>
{!! Form::close() !!}
</div>
</div>
</div>
</div>
<tr>
<th>{{ (($employees->currentPage() - 1 ) * $employees->perPage() ) + $key + 1 }}</th>
<td>{{ $employee->name }}</td>
<td>{{ $employee->email }}</td>
<td>{{ $employee->position->name }}</td>
<td class="position-btn-in-the-right input-prepend">
<a href="{{ route('employees.show', $employee->id) }}" class="btn btn-sm btn-default"><i class="fa fa-btn fa-eye"></i>View</a>
<a href="{{ route('employees.edit', $employee->id) }}" class="btn btn-sm btn-primary"><i class="fa fa-btn fa-pencil-square-o"></i>Edit</i></a>
<button class="btn btn-sm btn-danger" data-href="{{ route('employees.destroy', $employee->id) }}" data-toggle="modal" data-target="#confirm-delete"><i class="fa fa-btn fa-trash-o"></i>Remove</button>
</td>
</tr>
@endforeach
</tbody>
</table>
And my js:
$('#confirm-delete').on('show.bs.modal', function(e) {
$(this).find('.btn-ok').attr('href', $(this)(e.relatedTarget).data('href'));
});
Thanks in advance!
2
Answers
i was getting the same problem before , you are setting a model component with a static id wich will be repeated inside the @foreach , so for that you have to set a dynamic id for that component , try something like
so when the DOM load it will create a lot of modal component with such a different ids
and for the button you can just put this with no JS required
This code:
is wrong. Even if you change it to:
It’s not valid.
So, because you are looking for the button clicked to show your modal, you may use:
In other words, when you click on the button, document.activeElement is exactly the clicked button.
My example: