Adrian Enriquez Adrian Enriquez - 2 years ago 63
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:


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.


<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 class="modal-body">
<p>Click Add. After clicking add, open the modal again then click add again to see the problem.</p>
<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>
<!-- /.modal-content -->
<!-- /.modal-dialog -->
<!-- /.modal -->


// Append merge field to message textarea
$('#mergeFieldsModal').on('', function(event) {
var button = $(event.relatedTarget);
var messageId ='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 Source

Since you are attaching new event every time modal dialog box is opening. You need to remove it before adding new.'click').on('click', function(){

Make the above change and it will work

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download