user5005768Himadree
user5005768Himadree

Reputation: 1427

Why is the modal button calling multiple times?

I write a code for update button click that will show a bootstrap modal with 2 buttons cancel, delete.I noticed that after clicking update button the modal display with button.however if i press delete button on that modal then strangely the delete button call it self twice or more instead on 1.As a result the ajax is also firing twice.I thing there may be any event class.Here the sample code.

    <button type="button"   id="update" class="btn btn-success" style="display:none;">Update</button>
<div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal" id="cancel">Cancel</button>
    <button type="button"  class="btn btn-danger btn-ok" id="btn-delete">Delete</button>
</div>

$("#update").click(function (e) {
    e.preventDefault();
    $('#confirm-delete').modal("show");
}); 

$('#confirm-delete').on('show.bs.modal', function(e) {
     var instance = $(this);
     $("#btn-delete").click(function(event) {

         var data_x = 101;
         event.preventDefault();
         instance.modal('hide');
         $.ajax({
             url: 'delete_data.php',
             type: "post",
             async: true,
             data: ({
                 data_x: data_x
             }),
             success: function(data) {
                 alert(data);
             }
         });


     });

 });

please help me to understand it & resolve it.thanks

Upvotes: 1

Views: 2645

Answers (1)

isherwood
isherwood

Reputation: 61063

You're creating an additional click function every time you open the modal. Do it once:

$('#confirm-delete').one('show.bs.modal', function(e) {
// --------------------^
     $("#btn-delete").click(function(event) {

Alternatively, use event delegation and do it outside the modal callback (anywhere inside document.ready):

$(document).on('click', '#confirm-delete', function() {
    // ...

Upvotes: 4

Related Questions