Search code examples
jqueryajaxtwitter-bootstrapbootstrap-popover

Bootstrap popover does not toggle after changing its content


I have a row of buttons and on every click i want to fill the popover with data from an ajax call.

What i have done

   $(document).on('click','.foo', function (event){
   $(this).popover({
            html: true,
            trigger: 'manual',
            title:'Foo Title',
            placement: 'bottom',
            content: ''
}).popover('toggle');
    event.preventDefault();
    var id = $(this).attr('id').substring(21);
    getResults(id);
});

Now i can toggle the popover and run the function which brings to me the desired data.

    $.ajax({
        url: url,
        type: "get",
        success: function (response) {
           var $data = $(response);
           console.log($data);
           var data = $data;
           var popover = $('#foo' + id).attr('data-content',data).data('bs.popover');
           popover.setContent();
           popover.$tip.addClass(popover.options.placement);

        },
        error: function () {
            console.log("fail");
        }
    });

The popover opens correctly and the ajax data are appended correct. But the problem is that the popover stays opens and i cannot close it any more.


Solution

  • You're making the ajax call every time .foo is clicked regardless of whether or not the popover is supposed to toggle show or hide.

    $(document).on('click', '.foo', function (event) {
        var $this = $(this);
    
        $this.popover({
            html: true,
            trigger: 'manual',
            title:'Foo Title',
            placement: 'bottom',
            content: ''
        }).popover('toggle');
    
        event.preventDefault();
    
        $this.on('show.bs.popover', function () {
            var id = $(this).attr('id').substring(21);
            getResults(id);
        });
    });