Search code examples
javascriptjquerytwitter-bootstrappopover

Bootstrap popover only one time for multiple positions


I have a table on my website. I would like to give the user the possibility to easily add comments to each of the row.

For that i found a nice looking comment view on the internet.

here is an example:

<div class="popover-markup">
  <a href="#" class="trigger btn btn-default" data-placement="right">Popover link</a>
  <div class="content hide">
    code
  </div>

</div>


$('.popover-markup>.trigger').popover({
  html: true,
  title: function() {
    return $(this).parent().find('.head').html();
  },
  content: function() {
    return $(this).parent().find('.content').html();
  }
});

http://jsfiddle.net/dzr521qs/424/

This is basically exactly what i would like to have. But... I need a form inside of the comment view to post data to my server. And since i have around 50-300 Entries in the table, it would generate a ton of code if i have to place the code for the popover for every single row.

so my question is:

is it possible to define the popover once and show always the same popover but with different content for every row?

I would like to have a small icon on every row whith which i can open the popover and give over an id to the popover to load dynamic content.

hope someone have an idea.

thanks


Solution

  • You can add additional attribute to your popover link (say data-target) that will point to an element you want to display as content.

    You can extract data attribute value inside content() callback and use it to display different content.

    Example:

    // inside popover(...)
    content: function() {
        var contentSelector = $(this).data("target");
        if (contentSelector && $(contentSelector).length > 0) {
            return $(contentSelector).html();
        } else {
            return "<div class='alert alert-warning'>Please specify data-target attribute pointing to element in page</div>";
        }
    }
    
    // in your trigger add `data-target` attribute
    <a ... data-target=".content">...
    

    Here's an updated fiddle demonstrating that solution