Jennifer Michelle Jennifer Michelle - 2 months ago 24
jQuery Question

Bootstrap modal: event.relatedTarget (not updating)

I have a Bootstrap modal in which I want to update the appearance of the button that launched the modal. The 'relatedTarget' does not appear to update when a new button launches the modal.

Here's the Codepen

To reproduce the issue:


  1. Click first button to launch modal. Use radio button to apply a class to button. Close modal.

  2. Click second button to launch modal. Use radio button to apply different class to button. Close modal.



[Issue]: Both buttons get the same class. The first button will also change color.

$('#myModal').on('show.bs.modal', function (e) {

var origin = $(e.relatedTarget);

$("#modalButton").click( origin, updateButton );
function updateButton (event) {
var color = $('input[name="radio_color"]:radio').filter(':checked').val()
var origin = event.data;
origin.removeClass('blue').removeClass('red').addClass(color);
$('#myModal').modal('hide');
}
});


Thanks so much for any help resolving.

Answer

It's because you haven't unbound your previous click event (so they are just stacking up - so the second click will fire 2 events - the new one and the previously bound one)

Add this:

$("#modalButton").off('click');

Before you bind the new click and it should solve your problem

Updated Pen

Comments