Embedding a table inside a Bootstrap popover

I'm struggling with adding a table inside a Bootstrap popover. When I click on it, the table doesn't show up. This is my first time trying to insert HTML into a popover, so I don't know the correct way to do it. Any help would be appreciated. Thank you!

$(function(){
    $("[data-toggle=popover]").popover({
        html : true,
        content: function() {
          var content = $(this).attr("data-popover-content");
          return $(content).children(".popover-body").html();
        },
        title: function() {
          var title = $(this).attr("data-popover-content");
          return $(title).children(".popover-heading").html();
        }
    });
});
 <a role="button" class="btn btn-link btn-item black-text" data-toggle="popover" data-trigger="focus" data-placement="top" title="Currency Converter" data-content="Displayed rates are only for informational purposes and do not reflect on the actual rates you may be charged by the financial institution handling your transaction.
<table class='table table-condensed table-bordered'>
<tr><td>Euro</td><td>€79,123</td></tr>
<tr><td>GB Pound</td><td>£46,536</td></tr>
<tr><td>AU $</td><td>$123,456</td></tr>
</table>LLC accepts payment in US Dollars only. Rates do not include taxes, duties, shipping, insurance, or any other expenses associated with the purchase."><i class="fa fa-exchange"></i> Currency converter</a>

Answer №1

I found a solution that worked for me:

$(function() {
    $.fn.tooltip.Constructor.Default.whiteList.table = [];
    $.fn.tooltip.Constructor.Default.whiteList.tr = [];
    $.fn.tooltip.Constructor.Default.whiteList.td = [];
    $.fn.tooltip.Constructor.Default.whiteList.div = [];
    $.fn.tooltip.Constructor.Default.whiteList.tbody = [];
    $.fn.tooltip.Constructor.Default.whiteList.thead = [];

    $('[data-toggle="tooltip"]').tooltip({
        html: true,
        container: 'body'
    })
})

Answer №2

Here is an example that uses a table in a popover along with a toggle button: http://jsfiddle.net/z824fn6b/320/

<a href="#" class="btn btn-primary" tabindex="0" data-toggle="popover" data-trigger="focus" data-popover-content="#a1" data-placement="right">Popover Example</a>
<div id="a1" class="hidden">
  <div class="popover-heading">Title <span style="float:right;cursor:pointer;" class="fa fa-times" data-toggle="popover"></span></div>
  <div class="popover-body">
    <table style="width:100%">
      <tr>
        <td>Jill</td>
        <td>Smith</td>
        <td>50</td>
      </tr>
      <tr>
        <td>Eve</td>
        <td>Jackson</td>
        <td>94</td>
      </tr>
      <tr>
        <td>John</td>
        <td>Doe</td>
        <td>80</td>
      </tr>
    </table>
  </div>
</div>


$(function() {
  $("[data-toggle=popover]").popover({
    html: true,
    content: function() {
      var content = $(this).attr("data-popover-content");
      return $(content).children(".popover-body").html();
    },
    title: function() {
      var title = $(this).attr("data-popover-content");
      return $(title).children(".popover-heading").html();
    }
  });
});

Answer №3

Take a look at this example for guidance:

HTML structure:

<div id="myContent">
<table border="1" style="width:100%">
    <tr>
        <td>Amy</td>
        <td>Brown</td>
        <td>60</td>
    </tr>
    <tr>
        <td>Mark</td>
        <td>Miller</td>
        <td>72</td>
    </tr>
    <tr>
        <td>Sarah</td>
        <td>Clark</td>
        <td>88</td>
    </tr>
</table>

jQuery functionality:

$('[data-toggle=popover]').popover({

   content: $('#myContent').html(),
   html: true

}).click(function() {
   $(this).popover('show');
});

See it in action on jsFiddle: http://jsfiddle.net/39rwkzqL/8/

Answer №4

My approach is outlined below:

XHTML:

<div class="span12" style="margin-top: 150px;width:100%">
   <a tabindex="0" role="button" data-trigger="focus" class="btn-sm btn-info" data-placement="top" id="commentPopover"><i class="fa fa-comments" ></i> View</a>
   <!-- Popover 2 hidden content -->
   <div id="commentPopoverHiddenContent" style="display: none">
      <div>
         <table border="1" style="width:100%">
            <tr>
               <th width="30%">Comment date</th>
               <th width="70%">Comment</th>
            </tr>
            <tr>
               <td>12/03/2015 16:45</td>
               <td>*Username - Testing1</td>
            </tr>
            <tr>
               <td>12/03/2015 16:55</td>
               <td>*Username - Testing2</td>
            </tr>
            <tr>
               <td>12/03/2015 17:13</td>
               <td>*Username - Testing3</td>
            </tr>
         </table>
      </div>
   </div>
   <!-- Popover 2 hidden title -->
   <div id="commentPopoverHiddenTitle" style="display: none">
      Error comments
   </div>
 </div>

Javascript:

$(function(){
// Enabling Popover Example 2 - JS (hidden content and title capturing)
$("#commentPopover").popover({
    html : true, 
    content: function() {
      return $('#commentPopoverHiddenContent').html();
    },
    title: function() {
      return $('#commentPopoverHiddenTitle').html();
    }
});
});

Take a look at the demo here: http://jsfiddle.net/5bsykcqt/

Answer №5

Illustrating with the most recent Bootstrap v5.3, here is a demo featuring the utilization of the <table> element within a Popovers:

document.addEventListener('DOMContentLoaded', function () {
      const allowList = bootstrap.Tooltip.Default.allowList;
      allowList.table = [];
      allowList.thead = [];
      allowList.tbody = [];
      allowList.tr    = [];
      allowList.th    = [];
      allowList.td    = [];
  });
document.querySelectorAll('[data-bs-toggle="popover"]').forEach(popover => {new bootstrap.Popover(popover, {html: true})});
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c4a6ababb0b7b0b6a5b484f1eaf7eaf6">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dbb9b4b4afa8afa9baab9beef5e8f5e9">[email protected]</a>/dist/js/bootstrap.bundle.min.js"></script>
<button type="button" class="btn btn-lg btn-danger" data-bs-toggle="popover" data-bs-title="Popover title" data-bs-content="
<p>And here's some amazing content with<br/>line break.</p>
<ul>
  <li>Unordered Item 1</li>
  <li>Unordered Item 2</li>
</ul>
<table class='table table-sm table-bordered'>
  <tr>
    <th>Header 1</th>
    <th>Header 2</th>
  </tr>
  <tr>
    <td>Data 1</td>
    <td>Data 2</td>
  </tr>
</table>
It's very engaging. Right?
">Click to toggle popover</button>

Answer №6

When working with CSS3, there is a more streamlined approach available: utilize the display attributes below to mimic table-like behavior

.popover_container{
    display: table;
}
.popover_row{
    display: table-row;
}
.popover_column1{
    display: table-cell;
    text-align: left;
}
.popover_column2{
    display: table-cell;
    text-align: left;
}

From there, you can construct the popover content

$popover_content = "<div class='popover_container'>
                       <div class='popover_row'>
                           <div class='popover_column1'></div>
                           <div class='popover_column2'></div>
                       </div>  
                    </div>";

Finally, integrate it into your HTML code as shown below

echo ('<span class="material-symbols-outlined" data-bs-html="true" data-bs-toggle="popover" data-bs-trigger="hover" title="your titile" data-bs-content="'.$popover_content.'">youricon</span>')

Answer №7

After struggling to find a solution and realizing the existing answers were outdated, I stumbled upon this workaround:

const list = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))                  
              list.map((el) => {
                let opts = {
                  animation: false,
                }
                if (el.hasAttribute('data-bs-content-id')) {
                  opts.content = document.getElementById(el.getAttribute('data-bs-content-id')).innerHTML;
                  opts.html = true;
                  opts.sanitizeFn = function (content) {
                        return content
                    }
                }
                new bootstrap.Popover(el, opts);
              })

As referenced near the end of this page: Bootstrap 5 Documentation You have the option to customize your own sanitize function, ensuring that no content is removed if you simply return what was provided. Voilà!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am currently facing an issue with validating forms in JavaScript Document Object Model (DOM)

Whenever I click on a field and move to another one, the span tag turns red. Then, after pressing the submit button, an alert message pops up. However, if I turn the span red, fill in the field, and press the submit button, it shows success even if other f ...

Dynamic form name validation in Angular is crucial for ensuring the accuracy and

When it comes to validating a form in Angular, I usually use the ng-submit directive like this: <form name="formName" ng-submit="formName.$valid && submitForm()"></form> This method works well for forms with predefined names that I se ...

Designing an image transformation page by segmenting the image into fragments

Does anyone have insight into the creation process of websites like this one? Are there any plugins or tools that can assist in building something similar? ...

Position the buttons in the react children's application

**Looking for help on positioning Black Widow in the center-left and Hulk at the bottom left of the screen. I'm having trouble figuring it out, does anyone have any tips? Also, I only want to isolate the buttons to each picture. Not sure if I need to ...

The route seems to be downloading the page instead of properly rendering it for display

I'm facing a simple issue with my Express page - when I navigate to the FAQ route, instead of displaying the page it downloads it. The index page loads fine, and the FAQ page is the only other page available at the moment. I am using EJS templating, a ...

Creating a Select component in React without relying on the Material-UI library involves customizing a dropdown

Is there a way to achieve a material UI style Select component without using the material UI library in my project? I'm interested in moving the label to the top left corner when the Select is focused. export default function App({...props}) { retu ...

Why does the header still show content-type as text/plain even after being set to application/json?

When using fetch() to send JSON data, my code looks like this: var data = { name: this.state.name, password: this.state.password } fetch('http://localhost:3001/register/paitent', { method: 'POST&a ...

A collection of jQuery objects that consist of various DOM elements as their properties

Seeking a more concise and potentially more streamlined approach using jQuery. I have an object called lbl which represents a div. Inside this div, there is a span tag that contains the properties firstName and lastName of the lbl object. Here's how t ...

Having trouble moving to a different component in Angular?

In my application, I am facing an issue with navigating from List to Details component by passing the ID parameter. It seems that there is no response or error when attempting to call the relevant method. Below, you can find the code snippets related to th ...

The cart total variable in Vuejs is coming back as NaN

I'm currently in the process of creating a cart system using vuejs and I've encountered an issue where my total variable is displaying NaN instead of calculating the total price of all products. Below is the function responsible for calculating ...

Generating links within a popover using an array in Rails 4

Within my application, Users have the ability to recommend other Users' profiles seamlessly. The functionality related to models and associations is working perfectly, as I am able to identify which users have recommended the current_user's profi ...

Regular expression is used to limit input to integers only, specifically numbers between -130 and 30

Completed the regex for 0 to 50 ^(?:[1-9]|[1-4][0-9]|50)$ The current regex is functioning correctly. Next step is to create a regex that includes negative numbers, allowing for values between -130 and 30 without any decimal points. ...

Executing Javascript code that has been retrieved using the XMLHttpRequest method in a

Would it be feasible to modify this code to function recursively if the redirects to the js file that needs to be executed? function loadScript(scriptUrl) { var xhr = new XMLHttpRequest(); xhr.open("GET", scriptUrl); xhr.onready ...

Passing props from a Higher Order Component (HOC) to child components in next.js using get

I am looking to implement an HOC (Higher Order Component) for pages within my application that can provide some information stored in local storage, especially when the pages are not being server-side rendered. The challenge I'm encountering is that ...

The reactivity of VUE 3 arrays is not being updated, but individual array elements accessed using array

Currently facing an issue while trying to connect a dynamically updating array of objects to a Konva circle. The circles are appearing as expected, but the problem arises within a for loop where I update player locations based on a "tick". While setting th ...

File handling in Angular 2 using Typescript involves understanding the fundamental syntax for managing files

Would someone be able to explain the fundamental syntax for reading and writing text files, also known as file handling in TypeScript? If there is a corresponding link that anyone could provide, it would be greatly appreciated. ...

Error: JSON encountered circular structure when attempting to serialize an object of type 'ClientRequest' with a property 'socket' that references an object of type 'Socket'

Encountering an error while attempting to make a POST request to my TypeORM API using axios: TypeError: Converting circular structure to JSON --> starting at object with constructor 'ClientRequest' | property 'socket' -&g ...

Determining the typing of a function based on a specific type condition

I have created a unique type structure as shown below: type Criteria = 'Criterion A' | 'Criterion B'; type NoCriteria = 'NO CRITERIA'; type Props = { label?: string; required?: boolean; disabled?: boolean; } & ( | ...

Tips for removing the y-axis line in ChartJs

How can I hide the y axis line in a bubble chart? I attempted to use the code snippet below but it did not work as expected. yAxes: [{ angleLines: { display: false } }] ...

What is the best way to detect the presence of the special characters "<" or ">" in a user input using JavaScript?

Looking to identify the presence of < or > in user input using JavaScript. Anyone have a suggestion for the regular expression to use? The current regex is not functioning as expected. var spclChar=/^[<>]$/; if(searchCriteria.firstName.m ...