(specific) $.load() with datatable causes error when removing row through element

(specific) $.load() with datatable causes error when removing row through element

ChickenMobileChickenMobile Posts: 7Questions: 3Answers: 0

I'm getting an error when trying to remove a particular row from a reinitialized table from a jquery remote load.

It can be reproduced by running the below code:

<html>
<head>
    <script src="jquery-3.2.1.min.js"></script>
    <script src="jquery.dataTables.js"></script>
</head>

<body>
    <div class="container"></div>
    <button onclick="redoContainer()">Redo Container</button>

    <script>
        var tableStr = "<table id='example'><thead><tr><th>Column</th><th>Remove</th></tr></thead> <tbody>";
        for (var i = 0; i < 5; i++) {
            tableStr += "<tr><td>Test " + i + "</td><td><button class='removeBut'>Remove Row</button></td></tr>";
        }
        tableStr += "</tbody></table>";

        tableStr += "<script> " +
            "$(function () { " + 
                "var table = $('#example').DataTable();" +

                "$(document).on('click', '.removeBut', function () {" +
                    "var butRow = $(this).parent().parent();" +
                    "table.row(butRow).remove();" +
                    "table.draw();" +
                "});" +
            "}); " + 
        "<\/script>";

        function redoContainer() {
            $(".container").empty().append(tableStr);
        }
    </script>
</body>
</html>

Fix:
Change $(document).on('click'... to $('.removeBut').click(... or var butRow = $(this).parent().parent() to var butRow = $(this).parent().parent().index()

Answers

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    Hi @ChickenMobile ,

    Does that "Fix" comment at the bottom mean you've resolved this?

    Cheers,

    Colin

This discussion has been closed.