1

I am trying to load data in Bootstrap Modal using ajax request. This is my sample code : http://jsfiddle.net/tejashsoni111/f97gpwte/2/

HTML :

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary btn-lg" id="button">
  Launch demo modal
</button>
<div id="exec_count"></div>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <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>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>

JS :

var count=0

$("#button").click(function(){
    $('#myModal').on('shown.bs.modal', function (e) {
        count++;
        jQuery("#exec_count").append("<span>"+count+"</span></br>");
    });

    $('#myModal').modal('show');

    $('#myModal').on('hide.bs.modal', function (e) {
        count=0;
        jQuery("#exec_count").append("</br>");
    });
});

The problem is, after each time button is pressed the event call is increased by one. So every time number of ajax calls are also increased with the event call. In the example, I have replace the ajax code with display event call count.

I am not able to find any solution for avoiding extra calls.

Any help will be appreciated, Thanks in advance.

3
  • 4
    You need to hook up the events outside the click event. Basically you are adding an event handler every time you click.
    – Brian
    Commented Dec 29, 2014 at 12:56
  • 2
    Binding event handler inside another event handler is very bad idea itself in most cases. And it causes all kind of troubles in situations like this.
    – Regent
    Commented Dec 29, 2014 at 12:56
  • Ok now I got it, thanks for response. Commented Dec 29, 2014 at 13:04

1 Answer 1

1

The event handlers is being added every time the button is being clicked. You will need to move your event handlers outside of the click event.

var count=0

$('#myModal').on('shown.bs.modal', function (e) {
    count++;
    jQuery("#exec_count").append("<span>"+count+"</span></br>");
});

$('#myModal').on('hide.bs.modal', function (e) {
    count=0;
    jQuery("#exec_count").append("</br>");
});

$("#button").click(function(){
    $('#myModal').modal('show');
});

Not the answer you're looking for? Browse other questions tagged or ask your own question.