1

I am newbie to jquery and javascript. Currently Iam using jquery datatables and have a requirement to add a checkbox column to my datatable dynamically. I was browsing and found this link useful. However, the solution given in this thread below adds the additional column at the end. But I need the checkbox column as my first column. Please refer to the link below which contains a hack at the end which I am using currently to add a "" ao every row in the array.

Link to related query

Please suggest me a better solution to solve my problem. I do not want the server to send the extra column in the response.

1 Answer 1

3

I'm assuming you're using sAjaxSource to get the data from the server. If you don't want to send an extra column, you could manually move your data one column further, but you'd still have to have an extra column in your html table. Something like this:

Let's say, you have a json formatted like the following:

{
    "aaData":
    [
        [
            "1",
            "Alice"
        ],
        [
            "2",
            "Bob"
        ]
    ]
}

And you have a table with 3 rows, first one reserved for checkboxes:

<table>
    <thead>
        <tr>
            <th>Checkbox</th>
            <th>Id</th>
            <th>Name</th>
        </tr>
    </thead>
</table>

Then, when creating a dataTable, in your aoColumns, you'd have to manually adjust where you want each piece of data to go. By default, DataTables just goes through array indexes, starting with 0 and assigns it to the corresponding column, so let's reassign them:

"aoColumns": [
        { "mData": null,
          "mRender": function(){
            return '<input type="checkbox"/>';
          }
        },
        { "mData": 0 },
        { "mData": 1 }
    ]

Sending an empty record to fill up a row simply lets you avoid assigning mData manually.

Sign up to request clarification or add additional context in comments.

2 Comments

I followed your code snippet, but I am getting an error as below on my console: SyntaxError: invalid property id: {"mData": 0 }, Please help me where I am going wrong.
I forgot a curly brace after mRender part. Fixed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.