How to get the ID of the data by clicking on the row.

How to get the ID of the data by clicking on the row.

ynynloxxynynloxx Posts: 14Questions: 6Answers: 0

Hey people,

I am trying to receive the ID of the data shown in the row (not row ID), when I click on it. Currently the alert returns that it is undefined when I click on the row. I am using django rest framework.

My code looks like this:

    <script type="text/javascript" charset="utf8">
        var table = $('#table_id').DataTable();

        $(document).ready(function() {
            $('#table_id').DataTable({
                "ajax":{
                    "url": "{% url 'lagerverwaltung:articles-list' %}",
                    "dataSrc":"",
                },
                columns: [
                    { data: "id" },
                    { data: "name"},
                    { data: "image" },
                    { data: "size" },
                    { data: "color" },
                    { data: "number_of_pieces" },
                ],
                rowId: 'id',
            });

            $('#table_id tbody').on( 'click', 'tr', function () {
                var id = table.row(this).id();
                alert( 'Clicked row id '+id );
            } );
        } );

I hope someone can help me.

Kind regards,
Yin-yin

Answers

  • kthorngrenkthorngren Posts: 21,147Questions: 26Answers: 4,918

    Likely you are getting the console error:

    Uncaught ReferenceError: table is not defined

    Add this to your init code:

            var table = $('#table_id').DataTable({
                "ajax":{
                ......
    

    Looks like the rest should work.

    Kevin

  • ynynloxxynynloxx Posts: 14Questions: 6Answers: 0

    Hey Kevin,

    thanks it helped.

    Yin-yin

This discussion has been closed.