Responsive Columns Button Error
Responsive Columns Button Error
New to Javascript but not programming:
Have have a datatable that is responsive. The last column is a button and opens a modal window with other datatables on it. I need the data associated with the row. Everything works great until I size the window so that the button is wrapped.
var table = $('#userTable').DataTable( {
responsive: true,
select: true,
processing: true,
dataType: 'json',
ajax: {
url: "{{ url_for('users_page.users_data') }}",
method: 'post',
data: function ( args ) {
return {"data": JSON.stringify(args)};
}
},
columnDefs: [
{
orderable: false,
visible: false,
searchable: false,
targets: [0,5]
},
{
render: function( data, type, row ) {
if(row['admin'] == true) {
return "<i class='fa fa-fw fa-key' style='color:#333'></i> " + data;
} else {
return data;
}
},
targets: [1]
},
{
orderable: false,
searchable: false,
targets: [6]
}
],
columns: [
{ data: 'id_user' },
{ data: 'username' },
{ data: 'first_name' },
{ data: 'last_name' },
{ data: 'email' },
{ data: 'admin' },
{ data: null, className: 'center',
defaultContent: "<button type='button' class='btn btn-primary' data-toggle='modal' " +
"data-target='#keysModal'>Keys</button>"}
]
} );
The above table creates a null column at the end that will be used to toggle the modal.
$('#userTable tbody').on( 'click', 'button', function () {
var data = table.row( $(this).parents('tr') ).data();
var user_id = data['id_user'];
keyLoader(data['id_user']);
} );
That works
That doesn't because the row has changed.
Is there a better way of registering the button and being able to access the data of the row it is associated with?
This question has an accepted answers - jump to answer
Answers
Try:
If that works, I'll explain why! If it doesn't, could you give me a link to the page showing the issue so I can experiment a little with it please?
Allan
Woohoo! That did the trick.
So for those interested. Let me see if I get this right:
Which makes sense, but I thought in my original was getting the row with the "tr" element.
So the reason that works is that when the button is in the responsive view, it is actually passing the
li
element to DataTables as the cell selector (fromthis.parentNode
). DataTables' cell selector is smart enough to know to be able to get the original cell from that node (based on information that Responsive adds to it), thus letting you select the cell, then the row from the cell.You could use
table.row( this.parentNode )
in the Responsive view - that would work as well as thecell()
selector. But it wouldn't work in the standard table view, sincerow()
will not accept a cell as a selector.Hence the need to use
cell()
in order to be able to usethis.parentNode
as common to both methods.Allan