How To Change A Bootstrap Popover Title And Content Dynamically

Typically, when creating a bootstrap popover, you would declare, initialize and call it like this:

    Do Something
    $(function() {
        $('[data-toggle="popover"]')({
            trigger: 'manual',
            placement: 'auto top',
            delay: { show: 500, hide: 500 }
        });
    });

    function doSomething() {
        $('#do-something-popover').popover('show');
    }

However, sometimes you want to change the content of the popover dynamically, based on some results in the call to, in this case, doSomething() function. A prime example would be an ajax call where you want to show either a success or an error message but don’t want to declare two popovers and simply want to change the title and content of the existing one dynamically. This can be achieved quite easily:

    function doSomething() {
        $.ajax({
            url: 'http://.../Test'
            type: 'get',
            ...
            success: function(data, status, xhr) {
                $('#do-something-popover')
                    .attr('data-original-title', 'Success!')
                    .attr('data-content', 'Got the page!')
                    .popover('fixTitle')
                    .popover('show');
            },
            error: function(xhr, status, error) {
                $('#do-something-popover')
                    .attr('data-original-title', 'Error!')
                    .attr('data-content', 'Error getting the page!
' + error) .popover('fixTitle') .popover('show'); } }); }

Note the call to popover’s fixTitle to make sure the title gets updated. This is newbie stuff but hope this helps someone!
See also a Reference from W3Schools on Boortrap Popover or Popover Documentation From Bootstrap.

This entry was posted in Bootstrap and tagged , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *