Franc
Franc

Reputation: 5494

Get the element whose click opened a Bootstrap Modal dialog

How do I know which button triggered the opening of a Bootstrap Modal Dialog?

<a href="#" data-toggle="modal" data-target="#myModal">
    Button 1
</a>  
<a href="#" data-toggle="modal" data-target="#myModal">
    Button 2
</a>

Javascript

$('#myModal').on('shown.bs.modal', function () {
  var triggerElement = ???
})

Upvotes: 11

Views: 8650

Answers (1)

tmg
tmg

Reputation: 20413

Its documented here

$('#myModal').on('shown.bs.modal', function (event) {
     var triggerElement = $(event.relatedTarget); // Button that triggered the modal
});

Edit: As noted in comments, if buttons are dynamically generated we can attach an event listener to document:

$(document).on('shown.bs.modal', '#myModal', function (event) {
     var triggerElement = $(event.relatedTarget); // Button that triggered 
});

Upvotes: 24

Related Questions