Bootstrap modal relatedTarget is undefined

Bootstrap modal relatedTarget is undefined

I am trying to get the clicked element using the property relatedTarget of the show.bs.modal event. It’s always getting undefined though.
This is what I have:
$(“#curCarSelect”).on(‘click’, function(e) {
$(“#curCarModal”).on(‘show.bs.modal’, function(event) {
modalOpenedby = event.relatedTarget;
alert(modalOpenedby);
}).modal(‘toggle’);
});

Solutions/Answers:

Solution 1:

try:

$("#curCarSelect").on('click', function(e) {
   $modal.modal('toggle', $(this));
});

where $modal is your modal element to open, then:

$modal.on('show.bs.modal', function (event) {
   var button = $(event.relatedTarget) // Button that triggered the modal
})

Solution 2:

Per the documentation:

If caused by a click, the clicked element is available as the relatedTarget property of the event.

But you’re just calling .modal('toggle'). That doesn’t involve any click event, hence why relatedTarget in undefined in your case.

Solution 3:

If you need to use event.relatedTarget in you dynamically opened modal then you can pass the target as a second argument in the modal function.

$("#curCarSelect").on('click', function(e) {
    $("#curCarModal").modal('toggle', $("#curCarSelect")); 
});

Solution 4:

I make it worked for me. Try this:

$("#curCarSelect").on('click', function(e) {
    $("#curCarModal").on('show.bs.modal', function(event) {
        modalOpenedby = event.relatedTarget; 
        alert(modalOpenedby);
    }).modal('toggle', e);
});

Solution 5:

Workaround for this worked for me on bootstrap 2:

$("a[data-toggle='modal']").on('click', function(e) {
    $_clObj = $(this); //clicked object
    $_mdlObj = $_clObj.attr('data-target'); //modal element id 
    $($_mdlObj).on('shown.bs.modal',{ _clObj: $_clObj }, function (event) {
           $_clObj = event.data._clObj; //$_clObj is the clicked element !!!
           //do your stuff here...
    });
});

Solution 6:

try this:

$('#curCarModal').on('shown.bs.modal', function () {
    modalOpenedby = event.relatedTarget; 
});

$("#curCarSelect").on('click', function(e) {
    $("#curCarModal").modal('toggle'); 
    alert(modalOpenedby);
});

Related:  How do i make two bootstrap buttons side by side?

References