Dean219 Dean219 - 5 months ago 51
Javascript Question

Bootstrap set popover content

I have been trying to find a way to dynamically modify the content of a bootstrap popover using Javascript, however the method i have come across so far have not worked :

<!--object with the popover-->
<input id="popoverlist" type="text" name="poplist" placeholder="Enter data" data-html="true" data-content="" rel="popover" data-placement="bottom" data-original-title="pop list" >

$('#popoverlist').popover({
offset: 10,
trigger: 'manual',
animate: false,
html: true,
placement: 'left',
template: '<div class="popover" onmouseover="$(this).mouseleave(function() {$(this).hide(); });"><div class="arrow"></div><div class="popover-inner"><h3 class="popover-title"></h3><div class="popover-content"><p></p></div></div></div>'

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


The methods i have been trying to use to set the html content are :

$('#popoverlist').data('bs.popover').html("<p>New content</p>");
//and using the inner HTML
document.getElementsByClassName("popover-content")[0].innerHTML = '<p>New content</p>';


However neither of those methods change the html data content. I would appreciate any help on this to point me in the correct direction :)

Answer

Your second idea works, but you need to invoke it after the popover-content has been created.

The popover isn't created until the first time it is shown, and is recreated after each call to show. Thus, you need to change the content after $(this).popover('show');.

I've included a snippet showing this in action:

$('#popoverlist').popover({
  offset: 10,
  trigger: 'manual',
  animate: false,
  html: true,
  placement: 'bottom',
  template: '<div class="popover" onmouseover="$(this).mouseleave(function() {$(this).hide(); });"><div class="arrow"></div><div class="popover-inner"><h3 class="popover-title"></h3><div class="popover-content"><p></p></div></div></div>'

}).click(function(e) {
  e.preventDefault() ;
}).mouseenter(function(e) {
  $(this).popover('show');
  
  // dynamically change content after show
  document.getElementsByClassName("popover-content")[0].innerHTML = '<p>New content</p>';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<input id="popoverlist" type="text" name="poplist" placeholder="Enter data"  data-html="true" data-content="" rel="popover" data-placement="bottom" data-original-title="pop list" >