bootstrap events provide us event.relatedTarget
inside the available events. I am using shown.bs.modal
. In normal cases event.relatedTarget
has the button object from where we click and activate the modal by using onlick event on the button like below.
$("#buttonId").click(function(){
$("#modalId").modal('toggle');
});
then we can use the following way to get the button
$('#modalId').on('shown.bs.modal', function(event) {
var button = $(event.relatedTarget); // Button that triggered the modal
});
Now i am working on a filemanager plugin in which i have context menu binding on the browsed files, and inside the context menu i have a menu item Rename
, when i click on rename i have to open the modal window and send the file name that I have to rename. I can send the filename via context menu options selection ie by clicking on the Rename option i can get the object of the file div which has the filename inside the attribute id, but this will not help because i need the file div object inside the bootstrap shown event and i am opening the modal by calling the function openRenameWindow(#clickedFileDivObject);
from with in the context menu call back function and inside the function i open the modal like below
function openRenameWindow{
$("#rename-file").modal('toggle');
}
now the problem is when i bind the event for the shown.bs.modal
the event object always have the relatedTarget
undefined . Can someone guide me how can i get the filename there.
As of my understanding, you need to pass something to your modal window, if I understood wrongly please correct me by adding a comment.
Simplest solution:
Your problem caused as you did not pass the button
object as a second param when you toggled the modal window for show/display:
//pass button object
$("#rename-file").modal('toggle', $("#buttonId"));
You can do the following scenario too:
Each link should have a class .rename
and you can save fileName
as data attribute in your button or a div next to your button, when you open the modal window pass the fileName
as a data attribute to it.
$(".rename").click(function(e){
e.preventDefault();
var $this = $(this);
var fileName = $(this).data("file");
$("#basicModal").data("fileName", fileName).modal("toggle", $this);
});
$("#basicModal").on("shown.bs.modal", function(e){
//data-fileName attribute associated with the modal added in the click event of the button
alert($(this).data("fileName"));
//my data-file associated with the button
alert($(e.relatedTarget).data("file"));
})
Demo in Codepen for both solutions:
If you need more options in modal windows, Here is a library that I wrote based on Bootstrap 4
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.