how do I pass the id
to my event here?
{
var tr = $(this).closest('tr');
var id = tr.children('td:eq(0)').text()
data: null,
render: function ( data, type, row ) {
return '<button id="btnAddNotes" type="button" class="btn btn-success" data-toggle="modal" data-target="#my_modal">Add Notes</button>';
}
},
and I’m reading it like this
$(document).on("click", "#btnAddNotes", function (e) {
//here is where I want to see the id i'm passing
}
EDIT
This is how I construct the column, and I want to use the id of the row for the column At Location
-> how would I set that up?
columns: [
{
title: "At Location",
data: "id" ,
width: "10%",
className: "text-center",
render: function (data, type, full, meta){
return '<input type="checkbox" name="id[]" value="' + $('<div/>').text(data).html() + '">';
}
},
{
title: "Notes",
render: function(data, type, row, meta) {
return '<button data-id="' +
row. + // I want to use the At Location value
'" class="btn" type="button">Add Notes</button>'; }
}
]
2
Answers
You can add it as a data- attribute.
Short Answer:
Use the DataTables API to populate the ID you want to use.
Longer Explanation:
You are already using the API in your column render function – so we can take advantage of that (I have simplified your HTML slightly):
In this case I use
meta.row
to get the unique DataTables row index (which starts at 0 for the first row).I assign it to the
data-id
attribute – but I could assign it to theid
attribute also, since the value is guaranteed to be unique for each row (and therefore for each button).I can access this using the following:
If you want to populate the
data-id
attribute with an actual value from the data row, then you can use therow
parameter instead of themeta
parameter.Here is a runnable demo, using an external Ajax data test source, courtesy of the
jsonpaceholder
web site:The above demo uses
row.title
in therender
function, just as an example.Warning: Depending on what you do with the selected data, you may run into problems. To be safe, you should probably only use a column where the values are guaranteed to be unique.
And you must guarantee uniqueness if you want to use the
id
attribute instead of adata-*
attribute.