Search code examples
javajquerytwitter-bootstrapappendpopover

Dynamic Bootstrap Popover Content


I have a link that is toggling a Bootstrap Popover:

<a href="#" data-toggle="popover" title="List of Stuff" data-rights="${result.itemId}">Toggle Popover</a>

Now on the back end, result.itemId contains a list of countries that I need to display in the popover. I have the popover call, and a for loop to list out all of the countries associated with result.itemId PLUS a console.log that is properly displaying all of the countries in the console, I just don't know how to have them display properly in the popover.

Here's my Javascript:

$(function () {
  $('[data-toggle="popover"]').popover({
    html: true,
    content: function(){
        var rights = $(this).data('rights');
        var countries = resultsCountries[rights];
        for (var i in countries) {
            $(".popover-content").append('<span>' + i + ' &ndash; ' + countries[i] + '<span/><br/>');
            console.log(i, countries[i]);
        }
    }
  })
})

Like I said, in the console, all of the countries that associated with this result.itemId are displaying as they should, so I am able to access the database the countries are stored in, I just don't know how to get them to display in the popover "popover-content".

I should add, that this is dynamic, so depending on the result.itemId, the content of the popover would be different.

Thank you in advance.


Solution

  • You have to return your elements in the content function (by adding spans to the variable on each iteration).

    Here is an example:

    $(function() {
    
      var resultCountries = ['Germany', 'France', 'Spain'];
    
      $('[data-toggle="popover"]').popover({
        html: true,
        content: function() {
          var result = $();
          for (var i in resultCountries) {
            result = result.add(('<span>' + i + ' &ndash; ' + resultCountries[i] + '<span/><br/>'));
            console.log(i, resultCountries[i]);
          }
          return result;
        }
    
      });
    
    });
    

    CODEPEN