Sorting column with checkboxes - javascript

I have a table that I am using jQuery Datatable for.
var myTable = $("#My-Table").DataTable({
"order": [2, "asc"],
"aoColumnDefs": [
{ "bSortable": false, "aTargets": [3] },
{ "bSearchable": false, "aTargets": [2, 3] }
]
});
Now, the column that I am trying to perform ordering on is a column that contains checkboxes, so on page load I am setting a data attribute for that td element and then ordering by that attribute. The attribute will either be 0 or 1.
#(if item.Active)
{
<td class="active-td" data-order="0">
#Html.DisplayFor(modelItem => item.Active)
</td>
}
else
{
<td class="active-td" data-order="1">
#Html.DisplayFor(modelItem => item.Active)
</td>
}
Now, the user has the ability to deactivate or activate records.. and when they do, I am changing the data-order appropriately... but when I call draw, it is not putting the rows that contain unchecked td elements at the bottom and rows that contain checked td elements at the top like it does on page load.
Here is my jQuery for when a user wants to deactivate.
var td = row.children('td.active-td').attr("data-order", 1); // changing td data attribute accordingly
myTable.cell(myTable.row(row), 2, {order: 'current'})
.data("<input disabled='disabled' class='check-box' type='checkbox' />")
.draw();
The .draw() is not reordering the table like it does on page load.
How do I accomplish this?
Here is what it looks like when I deactive someone:
I want that row to be ordered so that checked checkboxes be at the top, and the unchecked at the bottom.
UPDATE
<script src="https://cdn.datatables.net/plug-ins/1.10.16/sorting/custom-data-source/dom-checkbox.js"></script>
var myTable = $("#My-Table").DataTable({
"columnDefs":[
{
"targets": 2,
"orderDataType": "dom-checkbox"
}],
"aoColumnDefs": [
{ "bSortable": false, "aTargets": [3] },
{ "bSearchable": false, "aTargets": [2, 3] }
]
});

Avoid using data- attributes for ordering dynamic data, they are good only for static data.
Use dom-checkbox plug-in that allows to sort based on the checked state of checkboxes in a column.
Include appropriate plug-in JS file and use orderDataType option for the column containing checkboxes.
For example:
var myTable = $("#My-Table").DataTable({
// ... skipped ...
"columnDefs": [
{
"targets": 0,
"orderDataType": "dom-checkbox"
}
]
});
See this example for code and demonstration.

Related

Can't change style value on second page using DataTable

At the first Page I can see negative value (e.g. -11) being changed to red.
However, when I clicked to the second page, negative value didn't change to red.
My code as below:
$("#listReport").DataTable({
'aoColumnDefs': [{
'bSortable': false,
'aTargets': [-1]
}]
});
$('#listReport tbody td').each(function (index) {
var qtyvalue = $(this).html();
if (qtyvalue < 0) {
$(this).wrapInner('<strong style="color:red"></strong>');
}
});
Any idea what to change in my code so that pagination works well with color change of the negative values?
You can use columns.render instead of manually trying to do it. Try this
$("#listReport").DataTable({
'aoColumnDefs': [
{
'bSortable': false,
'aTargets': [-1]
},{
'targets': [1], // target column
"data": 1, // column index
"render": function ( data, type, row, meta ) {
if( type === 'display' ){
return '<strong style="color:red">'+data+'</strong>';
}
return data;
}
}
]
});

Populate a datatable starting from the second column

I have a datatable that retrieves json data from an api. The first column of the table should only contain a checkbox. However, when retrieving the data it populates the first column as well.
$.getJSON('https://api.myjson.com/bins/o44x', function(json) {
$('#parametrictable').DataTable({
data : json.data,
columns : json.columns,
columnDefs: [ {
orderable: false,
className: 'select-checkbox',
targets: 0
} ],
select: {
style: 'os',
selector: 'td:first-child'
},
order: [[ 1, 'asc' ]]
})
});
Is there any way that I can set that the data should only populate starting from the second column, leaving the first column to only contain the checkbox?
You can fix this issue by updating the api or in your js code just updating the data key value to null for first object in the json.columns array like:
$.getJSON('https://api.myjson.com/bins/o44x', function(json) {
json.columns[0].data = null;
json.columns[0].defaultContent = '';
$('#parametrictable').DataTable({
data: json.data,
columns: json.columns,
.... your rest of code
})
});
EDIT:
I meant what your suggestion only did was hide the data that was overlapping with the checkbox. I don't want it hidden. I want the first column to be, by default, only checkboxes. and the overlapping data should be on the 2nd column.
You can update your API like this to achieve that:
"columns": [
{
"data": null,
"defaultContent": ""
},
{
"data": "DT_RowId",
"title": "Id"
},
{
"data": "supplier",
"title": "supplier"
},
{
"data": "color",
"title": "color"
}
],
Or, you can update your code without modifying your API like:
$.getJSON('https://api.myjson.com/bins/o44x', function(json) {
// Add object for checkbox at first position
json.columns.unshift({"data": null, "defaultContent": ""});
$('#parametrictable').DataTable({
data: json.data,
columns: json.columns,
....your rest of code
})
});

jQuery DataTables Ordering By 2 columns

I am using jQuery DataTables to style and give functionality to one of my tables:
My Goal
Order by whether or not the type of funding is active or not.. which is what it is doing currently as you can see. Now, I would like to order the Funding column alphabetically.. so my wanted outcome should be:
Funding One
Funding Two
Funding Three
Funding Four
Alpha
Beta
Charlie
Test
test2
Here is what I have so far my datatables script:
var codeFundingTable = $("#Code-Funding-Table").DataTable({
"bPaginate": false,
"bFilter": false,
"aoColumnDefs": [
{ "bSortable": false, "aTargets": [2] },
{ "bSearchable": false, "aTargets": [2] }
],
"columns": [
{ "orderData": [1] },
{ "orderData": [0] }
]
});
So I am first ordering by column 1 (Active, 0-based) then by column 0 (Funding) but it is not doing it alphabetically.
How can I make this happen?
It is a guess since we have no sample data. For example, what is the value of "active" (besides a checkbox is rendered)? But I believe you can just do
var table = $('#example').DataTable({
order: [[1, 'asc'], [0, 'asc']]
})
active column is sorted first, if values is 0 and 1 asc should be used
first column is secondly sorted alpha, with respect of second column order
Here is a demo -> http://jsfiddle.net/0f9Ljfjr/949/ position is sorted first, then name is sorted within each position "type".
Try this on for size
"columns": [
{ "orderData": [1,0] },
https://datatables.net/examples/basic_init/multi_col_sort.html
In my case, what helped me is this.
I used data-order attribute to sort my tables.
data-order="[[ 0, "asc" ], [ 1, "asc" ]]

Make edit link on datatable with multiple column values and global search on single/custom column(s)

How to create an edit link with function having multiple parameter from the data columns returned from ajax.
I read about the render callback but it only gets one column value & I need 2.
I need something like the following pseudo code.
"columnDefs": [ {
"targets": [0,1],
"data": "0,1",
"render": function ( data, type, full, meta ) {
return ``
}
} ]
As I'm disabling global search on all column except one. I cannot use the above code that use targets property. I don't know how to achieve this, please guide.
Edit: Complete code
var datatable = $('#datatable').DataTable({
"ajax": "/get_data/",
"processing": true,
"serverSide": true,
"deferRender": true,
"columnDefs": [
{ "searchable": false, "targets": [ 0,2,3,4,5,6,7,8,9,10,11 ] }
]
});
You can access row data using full variable, for example full[0] or full[1].
However instead of generating links in HTML, I would retrieve row data in a click handler as shown below:
$('#example').DataTable({
"columnDefs": [
{
"targets": [0, 1],
"render": function ( data, type, full, meta ) {
return 'Edit';
}
}
],
// ... other options ...
});
$('#example').on('click', '.btn-edit', function(){
// Get row data
var data = $('#example').DataTable().row($(this).closest('tr')).data();
edit(data[0], data[1]);
});
I needed Edit link on first column, so I followed #Gyrocode.com answer and it works great.
I also wanted to use the global search for searching but only on one column. Datatable ColumnDef Documentation gave me the clue so I ended up doing as follows.
Here The complete code:
var datatable = $('#datatable').DataTable({
"ajax": "/get_data/",
"processing": true,
"serverSide": true,
"deferRender": true,
"columnDefs": [
{
"targets": 0,
"render": function ( data, type, full, meta ) {
return 'Edit';
}
},
{ targets: 1, searchable: true },
{ targets: '_all', searchable: false }
]
});

Is it possible to redefine columns (and things defined in settings) in js datatable via ajax call?

I am aware that thanks to fnReloadAjax or combination of fnClearTable() and fnAddData() I can reload some fresh data
but is it possible this way somehow to redefine settings of table, in particulary: columns names, which are hidden, which are visible?
UPDATE:
If you will decide for destroying the table the easier way as checking existence and destroying like this:
if $.fn.DataTable.isDataTable("#element") {
$('#element').DataTable().destroy();
}
can be just setting the property in DataTable definition: bDestroy: true
I think you can redfine the settings by destroying the dataTable altogether like:
//part1
$( "#element" ).dataTable({
"sPaginationType": "full_numbers",
"iDisplayLength": 25,
"aoColumnDefs": [
{ "bSortable": false, "aTargets": [ 0 ] } //cannot sort using column 1
]
});
----------
//part2
$( "#element" ).dataTable().fnDestroy();
$('#element').dataTable( {
"aoColumnDefs": [
{ "bVisible": false, "aTargets": [2] } //hiding the column 3
]
} );
Here I just destroyed the dataTable for no reason but you can link it with some event.

Categories