1

I have data below and I want to pass two variables (id, name) in the columns.render function in Datatables.

What I have now is only pass the id in the render function. I also want to pass name in the render function.

Thanks.

const myData = [
  { id: 2, name: "book" },
  { id: 5, name: "song" },
];

$("#example").DataTable({
  data: myData,
  columns: [
    {
      targets: 1,
      data: "id",
      render: function (data, type, row, meta) {
        return (
          "<button class='btn btn-default' data_id='" +
          data + //id is passed to here
          "'>" +
          "name" + //the name I want to pass to here.
          "</button>"
        );
      },
    },
  ],
});

1 Answer 1

4

You can do it using the row parameter of render function.

const myData = [
  { id: 2, name: "book" },
  { id: 5, name: "song" },
];

$("#example").DataTable({
  data: myData,
  columns: [
    {
      targets: 1,
      data: "id",
      render: function (data, type, row, meta) {
        return (
          "<button class='btn btn-default' data_id='" +
          data + //id is passed to here
          "'>" +
          row.name + //get the name using row parameter
          "</button>"
        );
      },
    },
  ],
});

More details about render function can be found at https://datatables.net/reference/option/columns.render

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

2 Comments

Thanks. Actually, I don't need to use the argument data, I can only use row to access my data obejct then.
Yes, you can also use row.id instead of data

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.