ColumnDefs not workin

ColumnDefs not workin

justivanjustivan Posts: 2Questions: 0Answers: 0

Can anyone tell me why the custom column won't appear? The date pulled from the api is rendering but the additional column isn't.

<script>
  $(document).ready(function () {
    $("#data").DataTable({
      ajax: "/api/data",
      columns: [
        { data: "name" },
        { data: "age", searchable: false },
        { data: "address", orderable: false, searchable: false },
        { data: "phone", orderable: false, searchable: false },
        { data: "email" },
      ],
      columnDefs: [
        {
          targets: -1,
          data: null,
          defaultContent: "<button>Click!</button>",
        },
      ],
    });
  });
</script>

Replies

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

    As you've got columns, just add in there, something like this:

          columns: [
            { data: "name" },
            { data: "age", searchable: false },
            { data: "address", orderable: false, searchable: false },
            { data: "phone", orderable: false, searchable: false },
            { data: "email" },
            {
              data: null,
              defaultContent: "<button>Click!</button>",
            },
          ],
    

    Colin

  • kthorngrenkthorngren Posts: 21,344Questions: 26Answers: 4,954

    The last column you defined is email. So that would be the -1 column. Datatables isn't going to add a column to the end with columnDefs.targets set to -1. You need to define it. Something like this should work:

          columns: [
            { data: "name" },
            { data: "age", searchable: false },
            { data: "address", orderable: false, searchable: false },
            { data: "phone", orderable: false, searchable: false },
            { data: "email" },
            {
              data: null ,
              defaultContent: "<button>Click!</button>",
            },
          ],
    

    You don't need columnDefs, just define the column as part of the columns definition. Also make sure you have 6 columns defined in your thead.

    Kevin

  • justivanjustivan Posts: 2Questions: 0Answers: 0

    Ahh yes! I tried adding it to the columns as well but did not work. Turns out I was forgetting something very basic which is adding the <thead> tag. Thank you both of you!

Sign In or Register to comment.