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

余生长醉 提交于 2019-11-30 20:25:19

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

It is because your code defines click event each time user opens modal. You need to define click event outside of 'show.bs.modal'. Another approach, which you need to use only if you cannot use the first one, is to off() click event, when user closes modal.

$('#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

    });
    $(this).on('hide.bs.modal', function() {
      btnMergeField.off('click');
    });

});

The javascript that binds the event is run everytime the modal is build, you need to unbind the event or find an better place in your code to bind the event

You need to add following code for unbind click event when hide model

// Trigger function when modal hide
$('#mergeFieldsModal').on('hide.bs.modal', function(event)
{
     var btnMergeField = $(this).find('#btnMergeField');
     btnMergeField.unbind("click");
});

Demo

Call

btnMergeField.unbind('click');

before binding the click handler. Otherwise the click handler, that you have bound on last dialog open is still active.

As an alternative you might bind the click handler somewhere globally, so that there's no need to call unbind()/bind() again and again. Something like this:

$("*").on('click', "div[id=mergeFieldsModal]", function(){
    ...
    return false;
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!