Datatable

Datatable

ilernetilernet Posts: 1Questions: 1Answers: 0

Hi, I have this code that makes a call to an external api to get the data and print it in a datatable.

The code works and returns the data of the api, but it does not print a button for each row of the table.

That is the problem I have.

Thanks in advance

<table id="example" class="display" style="width:100%">
    <thead>
    <tr>
        <th>Id</th>
        <th>Title</th>
        <th>Completed</th>
        <td>Edit</td>
    </tr>
    </thead>
    <tfoot>
    <tr>
        <th>Id</th>
        <th>Title</th>
        <th>Completed</th>
        <td>Edit</td>
    </tr>
    </tfoot>
</table>


<script type="text/javascript">
    $(document).ready( function () {

        $.ajax({
            url : 'https://jsonplaceholder.typicode.com/todos',
            type : 'GET',
            dataType : 'json',
            success : function(data) {
                bindtoDatatable(data);
            }
        });

    });

    function bindtoDatatable(data) {
        var table = $('#example').dataTable({
            "bAutoWidth" : false,
            "aaData" : data,
            "columnDefs": [ {
                "targets": -1,
                "data": null,
                defaultContent: '<div class="btn-group"> <button type="button" class="btn btn-info"> test </button></div>'
            } ],
            "columns" : [
                {"data" : "id"},
                {"data" : "title"},
                {"data": "completed"}
            ]
        })
    }

</script>

Answers

  • kthorngrenkthorngren Posts: 21,691Questions: 26Answers: 5,020

    Using columns you need to define all the columns in your table. Remove the columnDefs option and try this:

                "columns" : [
                    {"data" : "id"},
                    {"data" : "title"},
                    {"data": "completed"},
                    {
                    "data": null,
                    defaultContent: '<div class="btn-group"> <button type="button" class="btn btn-info"> test </button></div>'
                    }
                ]
    

    Kevin

This discussion has been closed.