row selected works in reverse
row selected works in reverse
Hello, I have a DataTable in which the select is single, and I need to retrieve which row is selected, but it works the other way around ... That is, with this:
console.log ($ ('# top_chart'). DataTable (). row ({selected: false}). data ());
I can get the one that is selected, but where it says false it should be true, right? But if I set it to true, it returns me undefined ...
This is my DataTable (generated via AJAX):
function analysis_attributes_list() {
$.ajax({
url: "/analysis/analysis_attributes_list",
type: "GET",
dataType: "json",
success: function (response) {
if ($.fn.DataTable.isDataTable('#top_chart')) {
$('#top_chart').DataTable().destroy();
}
$('#top_chart tbody').html("");
for (let i = 0; i < response["top_chart"].length; i++) {
let row = '<tr>';
for (let j = 0; j < response["top_chart"][i].length; j++) {
if (j !== 5) {
if (response["top_chart"][i][j] === true) {
row += '<td>' + '<input class="form-check-input" type="checkbox" value="" onchange="analysis_attributes_list_checkbox_handler(this)" checked>' + '</td>';
} else if (response["top_chart"][i][j] === false) {
row += '<td>' + '<input class="form-check-input" type="checkbox" value="" onchange="analysis_attributes_list_checkbox_handler(this)">' + '</td>';
} else {
row += '<td>' + response["top_chart"][i][j] + '</td>';
}
}
}
row += '</tr>';
$('#top_chart tbody').append(row);
}
$('#top_chart').DataTable({
"pageLength": 5,
"lengthMenu": [[5, 10, 20, -1], [5, 10, 20, 'All']],
"destroy": true,
"select": {
style: 'single',
},
"responsive": true,
});
$('#top_chart').off('click').on('click', 'tr', function () {
console.log($('#top_chart').DataTable().row({ selected: false }).data());
});
},
error: function (error) {
console.log(error);
}
});
}
This discussion has been closed.
Replies
Using the
selector-modifierof{selected: false}is returning all of the unselected rows, not the row you clicked. Since you are usingrow()instead ofrows()only one row is returned and the console.log statement is outputting the first row in your dataset.The
clickevent fires before the row is selected resulting inundefinedwhen using{selected: true}. Instead use theselectevent to get the selected row. See this example:http://live.datatables.net/sadudema/1/edit
It shows the
clickevent fires first and theselectevent displays the selected row.Kevin
Oh I understand. It is the first time that I use DataTable for something other than displaying data and I get a bit lost ... One thing, how could I, from a function, get the number of the selected row?
Thank you very much Kevin!
What is the
numberyou want? You can userow().index()to get the row index. You can userow().id()to get the id if you use therowIdoption.Kevin