Adrian Enriquez Adrian Enriquez - 6 months ago 14
HTML Question

Why I'm getting more than one on click event fire inside bootstrap modal

I'm getting some problem here and need some help. I think this is easy but I just can't figure it out myself what's happening. Please see fiddle below:

Fiddle



When I only open the modal and clicks it for the first time. It works normally, but when I reopened it, there goes the problem. It fires the on click event more than once.

HTML

<button data-target="#mergeFieldsModal" data-toggle="modal" data-message-id="#message" class="btn btn-info">Open Modal</button>
<div id="result"></div>

<div id="mergeFieldsModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h3 class="modal-title"><span class="ss-shuffle ss-icon"></span> Merge Fields</h3>
</div>
<div class="modal-body">
<p>Click Add. After clicking add, open the modal again then click add again to see the problem.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" id="btnMergeField" class="btn btn-primary">Add</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->


JS

// Append merge field to message textarea
$('#mergeFieldsModal').on('show.bs.modal', function(event) {
var button = $(event.relatedTarget);
var messageId = button.data('message-id');
var btnMergeField = $(this).find('#btnMergeField');

btnMergeField.on('click', function() {

$('#result').append('<p>Fired!' + '</p>'); // Add to DOM
$('#mergeFieldsModal').modal('hide'); // Hide Modal

});

});

Answer

Since you are attaching new event every time modal dialog box is opening. You need to remove it before adding new.

 btnMergeField.off('click').on('click', function(){

Make the above change and it will work

Comments