Search code examples
javascriptjquerytwitter-bootstrapdatatablesbootstrap-popover

Bootstrap Popover in JQuery Datatable doesn't work after search


I have a HTML table:

<table id="PeopleTable" class="table table-striped table-bordered">
<thead>
    <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Pop</th>
    </tr>
</thead>
<tbody>
    <tr><td>0</td><td>Michael</td><td><button class='popoverButton'>Popover</button></td></tr>
</tbody></table>

And I want to use the DataTables plug-in to have search, order and filter functionality. I also want to use Bootstrap to show a popover when the button is clicked, so I've tried this:

var peopleTable = $('#PeopleTable').DataTable({
            drawCallback: function () {
                $('.popoverButton').popover({
                    "html": true,
                    trigger: 'manual',
                    placement: 'left',
                    "content": function () {
                        return "<div>Popover content</div>";
                    }
                }).click(function (e) {
                    $(this).popover('toggle');
                    e.stopPropagation();
                });
            }
        });

The problem is: when I perform a search, column sorting or any operation with the DataTable, the Popover stops working.

Here is the fiddle if you want to try it.

Is "draw" the correct event to perform this or should I use another one? Am I missing any other thing?


Solution

  • Updated JS fiddle link - https://jsfiddle.net/dxrjm530/4/

    You just need to take out your click event of button, because after sorting, it is getting called twice, due to drawcallback method of datatable.

            $('#PeopleTable').DataTable({
                drawCallback: function () {
                    $('.popoverButton').popover({
                        "html": true,
                        trigger: 'manual',
                        placement: 'left',
                        "content": function () {
                            return "<div>Popover content</div>";
                        }
                    })
                }
            });
    
            $('#AddRow').on('click', function(){
                var peopleTable = $('#PeopleTable').DataTable();
                peopleTable.row.add(
                    ['1',
                    "David", 
                    "<button class='popoverButton'>Popover</button>"]
                ).draw();
            });
    
    
    
            $('table').on('click', function(e){
            if($('.popoverButton').length>1)
            $('.popoverButton').popover('hide');
            $(e.target).popover('toggle');
    
            });