Search code examples
javascriptjqueryruby-on-railsajaxpopover

Bootstrap Popover Content Duplicates on Each Open


I have a popover that is dynamically populated. When I close the popover and re-open it again, the data is duplicated. I think I have isolated part of the solution to .$tip.find('.popover-content')). I am not sure where it should go. I have tested and am not sure as none of the solutions have worked.

Popover Content - 1st Opening: enter image description here

Popover Content - 2nd Opening: enter image description here

jQuery:

$(".listcollect").on("click", function(event) {
    var listID = this.id;

    $.ajax({
        method: "GET",
        url: "/listing_collections/:id/listcollect",
        success: function(result) {
            var arrLen = result.length

            for (var i = 0; i < arrLen; i++) {
                var listingCollectionId = result[i]["id"];

                var $li = $("<li></li>");
                var $a = $('<a class="listing-collection-item"></a>');
                $a.attr("href", "javascript:void(0);");
                $a.data("listing-id", listID);
                $a.data("listing-collection-id", listingCollectionId);
                $a.text(result[i]["name"])
                $li.append($a)
                $(this).next().append($li)
            }
        }.bind(this)
    });

    return true;
});

HTML:

<div class="btn-group listcollect-wrapper">
   <a onclick="lcflash" class="listcollect dropdown-toggle" data-toggle='dropdown' type="button" id=<%= listing.id %>>Add to Listing Collection <span class="caret"></span></a>
   <ul class='dropdown-menu'>
   </ul>
</div>

Solution

  • Assuming $(this) is an <ul>, one way to solve this would be to empty the <ul> every time.

    Try: $("ul").empty(); at the beginning. Rather $(this).empty(); in your case.

    Ideal, I'd think you want to clear a pop over list when you close it, but it's your app behavior, you'll know better.

    Your code:

    $(".listcollect").on("click", function(event) {
        var listID = this.id;
    
        $(this).next().empty();//clears the list items.
    
        $.ajax({
            method: "GET",
            url: "/listing_collections/:id/listcollect",
            success: function(result) {
                var arrLen = result.length
    
                for (var i = 0; i < arrLen; i++) {
                    var listingCollectionId = result[i]["id"];
    
                    var $li = $("<li></li>");
                    var $a = $('<a class="listing-collection-item"></a>');
                    $a.attr("href", "javascript:void(0);");
                    $a.data("listing-id", listID);
                    $a.data("listing-collection-id", listingCollectionId);
                    $a.text(result[i]["name"])
                    $li.append($a)
                    $(this).next().append($li)
                }
            }.bind(this)
        });
    
        return true;
    });