Chris Yates
Chris Yates

Reputation: 243

Adding buttons to jquery datatables that will correspond to row data id

OK I'm using jQuery datatables

I have

$(document).ready(function() {
    $('#companylist').DataTable( {
       dom: "Bfrtip",
        ajax: {
        url: 'data/companylist-ajax.php',
        dataSrc: '',
    },
    aLengthMenu: [[10, 25, 50], [10, 25, 50]],
   bPaginate:true,
   scrollX: "100%",
   order: [[ 0, "desc" ]],
   scrollCollapse: true,
        "columns": [
            { "data": "company_id" },
            { "data": "regoffice_city" },
            { "data": "regoffice_country" },
            { "data": "is_customer" },
            { "data": "is_supplier" },
            {"data": null,
            "defaultContent": "<a href=' + data[0] +'><i class=\"fa fa-fw fa-times\" style=\"color:red\"></i>Delete</button>",
            "targets": -1
          }
        ]
    } );
} );

What I am trying to do is that the button href will contain the company_id for the row of data being displayed However all it displays is localhost/ + data[0] + in the url I have tried company_id and other things I can think of but nothing works

Upvotes: 1

Views: 57

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

defaultContent only accepts a string, and it has no knowledge of the data within the row.

To achieve what you require, use render() instead. This takes a function which accepts the current row's data and returns the HTML string to be displayed within that column. Try this:

{
  data: null,
  render: function(data) {
    return '<a href="' + data[0] + '"><i class="fa fa-fw fa-times" style="color: red"></i>Delete</button>';
  }  
  targets: -1
}

Also note that I fixed the quotes, so you don't need to escape the inner ".

Upvotes: 1

Related Questions