Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 = ???
})
like image 563
tocqueville Avatar asked Sep 22 '16 20:09

tocqueville


People also ask

How to open bootstrap modal on button click?

To open Bootstrap modal on button click, you have to use the jQuery modal ('show'). You can can also display Bootstrap modal when someone clicks on button by adding the Bootstrap classes data-target and data-toggle. See this Simple Example ➜ Click me to Open Modal Using jQuery

How to find the click event of a modal using jQuery?

You have to use the id of the <button> element in jQuery to find the click event of the button. After that, apply the jQuery modal ('show') to the modal by using the modal id. So, assign a unique id to both the button and modal. Are you sure you want to continue?

How do I add a button to a modal pop up?

The short answer is: use the Bootstrap attributes data-backdrop and data-keyboard to add to the button element that opens the modal popup on click. You can also use the jQuery options backdrop and keyboard to…

How do I add a button to a bootstrap element?

The short answer is: use the Bootstrap button size classes to add to the button element as given below: .btn-lg .btn-md .btn-sm .btn-xs (Removed in Bootstrap 4 but you can use with Bootstrap 3 given below) Bootstrap… very easy example. I am so happy to see this type of example.


1 Answers

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 
});
like image 79
tmg Avatar answered Oct 12 '22 11:10

tmg