Reputation: 713
I have few button in the BS modal dialog and I wanted to initialized the events for these buttons after the modal is shown. This is working.
But the issue is, whenever I open the modal again ( close and open again ) the event initialized again. Because of this, event trigger several times ( equal to the times the event initialized ). If I open the modal 3 times the event trigger 3 times
$('#mymodal').on('shown.bs.modal', function() {
$(this).on('click', '.mybutton', function() {
alert('button clicked');
});
});
I want this to trigger this only once. Am I missing any ? How can i do this?
Upvotes: 1
Views: 3968
Reputation: 68
Try to remove click event before adding it.
$('#mymodal').on('shown.bs.modal', function() {
$(this).off('click', '.mybutton').on('click', '.mybutton', function() {
alert('button clicked');
});
});
Upvotes: 1
Reputation: 307
It is obvious, because a new click
event handler will be attached everytime the shown.bs.modal
event is triggered. So the solution is to move the event handler of click
somewhere outside the event handler of bs.shown.modal
.
$('#myModal').on('click', '.mybutton', function() {
alert('button clicked');
});
$('#mymodal').on('shown.bs.modal', function() {
//do something
});
Upvotes: 0
Reputation: 4420
Come up with a class name to indicate when the event has already been run for that button, and add it to the button when it's first run. Then check for the existance of that class when shown.bs.modal
fires. Your buttons have that class attribute? Don't run the event.
HTML:
<button type="button" class="btn btn-default" id="btnOpenModal" data-dismiss="modal">Open Modal</button>
<div class="modal fade" id="myModal">
<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">×</span></button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<p>One fine body…</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" id="btnClose" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
jQuery:
$('#btnOpenModal').click(function() {
$('#myModal').modal('show');
});
$('#myModal').on('shown.bs.modal', function() {
if ($('#btnClose').hasClass('test')) {
alert('Do the thing.');
} else {
$('#btnClose').addClass('test');
}
});
In the above example, when you click on the Open Modal button, the modal is shown, which fires the shown.bs.modal
event. When that's fired, it runs a simple if/else. If the Close button in the modal has the class 'test', pop an alert, otherwise add the class 'test' to that button. The first time it's run, no alert will show, but every time after that you'll get an alert.
That should get you pointed in the right direction.
Upvotes: 0