Bootstrap-confirmation not binding to dynamic elements?

810 views Asked by At

I have a form which uses AJAX to load dynamic content on the page. I am also using bootstrap-confirmation which I use to confirm a function which cancels a request. The confirmation works when the page is initially loaded.

Here is example code:

$(function() {

    $('[data-toggle=confirmation]').confirmation({
      rootSelector: '[data-toggle=confirmation]',
      popout: true
    });

    $(document).on('submit', '#some-form', function(e) {
      e.preventDefault();

      submitForm();
    });


    $('.static-element').on('click', '.cancel-request', function() {
      cancelRequest();
    });
}

The click event for .cancel-request works on the dynamic content, however the confirmation does not. I've tried changing the selector on the click handler to document but it makes no difference. I just can't find a way to bind the confirmation back to the dynamic element.

I've tried creating a callback on cancelRequest(), then reinitializing bootstrap-confirmation inside that but it made no difference. I also tried reinializing it inside complete: option but that didn't work either.

I tried Twitter BootStrap Confirmation not working for dynamically generated elements among a few other SO answers, but they doesn't work in my situation.

1

There are 1 answers

0
Michael Stewart On

Your JSfiddle was removing the element you were binding the JQuery listener to. An alternative approach would be to simply manipulate the element you were replacing so you don't have to battle with the transient elements.

//from your JS fiddle at https://jsfiddle.net/6wrb01u6/6/
$('[data-toggle=confirmation]').confirmation({
  rootSelector: '[data-toggle=confirmation]',
  // other options
});

$('#replace').on('click', '.do-something', function() {
  var html = "content";
  $.ajax({
    url: "/echo/html/",
    type: "POST",
    data: html,
    dataType: "HTML",
    success: function(data) {
      $('#replace>span').removeClass('do-something').removeClass('btn-primary');
      $('#replace>span').addClass('cancel').addClass('btn-danger');
      $('#replace>span').html('Cancel');
      $('.content').remove();
      $('#replace').append('<p class="content">New content</p>');
    }
  });
});

$('#replace').on('click', '.cancel', function() {
  $('.content').remove();
});