Reputation: 4543
I have 2 links (Add and Edit Customer Form) which trigger one same bootstrap modal. My question is how does that one same bootstrap modal detect it is from Add link or Edit link?
My current code is
<a href="" class="btn btn-default btn-rounded mb-4" data-toggle="modal" data-target="#modalCustomerForm">
Add New Customer
</a>
$('#modalCustomerForm').on('shown.bs.modal', function () {
$(this).find('form')[0].reset();
})
Upvotes: 1
Views: 1825
Reputation: 171690
Use the relatedTarget
property of the event
object to access the element that triggered the modal opening
$('#exampleModal').on('shown.bs.modal', function(e){
const buttonId = e.relatedTarget.id;
$(this).find('.modal-body').text(`Button id = ${buttonId}`);
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" ></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" ></script>
<!-- Button trigger modal -->
<button id="btn_1" type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Modal Button 1
</button>
<button id="btn_2" type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Modal Button 2
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body"></div>
</div>
</div>
</div>
Upvotes: 3