Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Insert Data Attribute into Bootstrap 5 Popovers

I have a series of buttons that contain a data-attribute that I want to insert into the popover they toggle.

HTML:

<button type="button" class="btn btn-yellow btn-deleteTeacher" data-bs-toggle="popover" role="button" data-username="farkle86">
   <i class="fa-solid fa-circle-xmark"></i>
</button>

JS:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$('[data-bs-toggle="popover"]').popover({
        html: true,
        container: 'body',
        placement: 'top',
        content: "<a href='teachers.asp?action=delete&user="+$(this).data('username')+"'>Click Here</a> to permanently delete this teacher."
    });

When I hover over the text link in the popover, the variable is ‘undefined’. I don’t know how to properly acquire the username data attribute.

>Solution :

The issue is because this within the popover() declaration isn’t the element the data attribute exists on. To get a reference to the element you would need to loop through them manually when declaring the popovers:

$('[data-bs-toggle="popover"]').each((i, el) => {
  let $el = $(el);
  $el.popover({
    html: true,
    container: 'body',
    placement: 'top',
    content: `<a href="teachers.asp?action=delete&user=${$el.data('username')}">Click Here</a> to permanently delete this teacher.`
  });
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading