'Bootstrap 4 not updating onclick attribute of popover
I am trying to create a popover in bootstrap 4 with a nested button inside it, but on updating the data-content
attribute of that popover with the button element it updates this element, but the onclick
attribute is missing.
I have tried using button
instead of anchor
tag, also tried using plain JavaScript to update the element, but the problem still persists.
I already have set popover property html: true
.
This is the js code for update:
function popoverUpdate(cart){
console.log("pop update");
var popoverdata = "<ol>"
for (i in cart){
popoverdata +="<li>Item :" + i + ", Quantity : " + cart[i] + "</li>";
}
popoverdata += "</ol><a href='#' onclick='console.log(5);' class='btn btn-secondary'>Hello</a>";
$('#cartVal').attr('data-content', popoverdata);
$('#cartVal').popover('show');
}
HTML element whose data-content
I am updating:
<button class="btn btn-primary m-lg-2" title="In Cart" id="cartVal" data-content="this is default content" data-toggle="popover" data-placement="bottom"
data-trigger="focus">Cart(0)</button>
Updated element as expected:
<a href='#' onclick='console.log(5);' class='btn btn-secondary'>Hello</a></pre>
Instead updates to:
<a href="#" class="btn btn-secondary">Hello</a>
As you can see, the onclick
attribute is missing.
Solution 1:[1]
Here's a hack. First, enable the data-html attribute, then you setup an event listener for clicks on your button, and finally prevent the default behavior
function popoverUpdate(cart){
console.log("pop update");
var popoverdata = "<ol>"
for (i in cart){
popoverdata +="<li>Item :" + i + ", Quantity : " + cart[i] + "</li>";
}
popoverdata += "</ol><a href='#' class='btn btn-secondary popoverButton'>Hello</a>";
$('#cartVal').attr('data-html', true);
$('#cartVal').attr('data-content', popoverdata);
$('#cartVal').popover('show');
document.querySelectorAll('.popover-body a.popoverButton').forEach((button, index) => button.addEventListener('click', (event)=>{
event.preventDefault();
console.log(5);
//put the rest of your code here
}));
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |