Is it possible to set a row on a fixed position? For example, we have now a total row, and we always want the total on top, after sorting etc.
Is there a plugin for this?
We have tried to do this in the onLoadComplete by redrawing the whole table like so:
var rowIDs = $(this).getDataIDs();
var rowID, columnID;
$(this).clearGridData();
for (rowID in rowIDs) {
for (columnID in data.rows[rowID]) {
$(this).addRowData(rowIDs[rowID], data.rows[rowID], (data.rows[rowID][columnID].first ? 'first' : null));
break; // Only do this for the first column
}
}
but that is bad for performance, we have thousands of rows.
after Oleg's comment:
The total row is just a row from our dataset. The dataset has this format:
Columns: 'Network', 'Clicks', 'Views'
data = [
{
'Network': {value:'Google'}, 'Clicks': {value:38392882}, 'Views':{value:3939922}
},
{
'Network': {value:'Sanoma'}, 'Clicks': {value:177883}, 'Views':{value:39293}
},
...
,
{
'Network': {value:'Total'}, 'Clicks': {value:993832732223}, 'Views':{value:3932293939}, 'first': true
},
...
]
}
So we set in our datarow which row we want to have on top ('first':true).
By processing, we use that to set in on top of the table. Hopefully this is more understandable :)
Thanks in advance,
Eddy
The footer are placed in the div with the class "ui-jqgrid-sdiv" and it is placed typically below the div with the class "ui-jqgrid-bdiv" where the main grid contain are placed. So to move the footer on top of page you need to move the the footer div. Additionally you should place bottom border in the style which you need. The code could be like the following:
$('div.ui-jqgrid-sdiv').css({
"border-bottom-style":"solid",
"border-bottom-color":"#a6c9e2",
"border-bottom-width":"2px"
}).insertBefore($('div.ui-jqgrid-bdiv'));
as the result you will receive
See the demo live here.
Related
I have setup my table in Tabulator with responsiveLayout:"collapse" and responsiveLayoutCollapseStartOpen:false.
My table display properly with collapsed columns.
I added formatter:"responsiveCollapse" as column and I properly get the column with + and - icons and can manually expand/collapse the columns.
But for usability on a smartphone, the icon renders really a bit small.
I want to add to expand/collapse based on callback rowClick.
I found responsiveCollapse and toggleList in tabulator.js, so I think I know what needs to happen. However I am totally struggling how to return it out of rowClick.
Thank you very much for a hint in advance.
In the tabulator constructor I have:
columns:[
{ formatter:"responsiveCollapse", width:30, minWidth:30,
hozAlign:"center", resizable:false, headerSort:false, responsive:0 },
{ title:"Ren.", field:"Race_Number", sorter:"number",
hozAlign:"center", minWidth:60, widthGrow:1, responsive:0 },
]
And basically I want to achieve the some functionality as formatter:"responsiveCollapse" in rowClick:
rowClick:function(e, id, data, row){
//trigger an alert message when the row is clicked
//what to do here to achieve same as formatter:"responsiveCollapse"
},
You could copy some of the code from the built-in responsiveCollapse formatter to achieve this. It will involve accessing some private variables, which is a bit naughty, but it will do the job:
rowClick:function(e, id, data, row){
var config = cell.getRow()._row.modules.responsiveLayout; //get the responsive config object for the row
var collapseEl = config.element; //get the collapsible element for the row
if(collapseEl){ //check if the row has any collapsed data
config.open = !config.open; toggle the open state
//toggle the collapse element
if(config.open){
el.classList.add("open");
collapseEl.style.display = '';
}else{
el.classList.remove("open");
collapseEl.style.display = 'none';
}
}
}
this was very helpful, remember to comment out "toggle the open state" and also update
el.classList.remove("open");
to
collapseEl.classList.remove("open");
I want to include datatable information in the print view.
Example I want to show this information in the print view: Showing 1 to 9 of 9 entries
Any help will be appreciated.
I've just played with the print option myself to see if I can wing it; including the footer didn't do much but add the same footer to the bottom of the table in print view; however; if you use the custom message you may be able to produce a good result; you can for example set a custom message showing total entries above or below your printed document.
$(document).ready(function() {
$('#example').DataTable( {
dom: 'Bfrtip',
buttons: [
{
extend: 'print',
messageBottom: function () {
var oTable = $('#example').DataTable();
var info = oTable.page.info();
var count = info.recordsTotal;
return 'Showing total entries of ' + count;
}
}
]
} );
});
You can play with either messageBottom or messageTop; or display both with two different messages.
In jquery datatable, single check box should be selected.
This link is working fine.
But above link is using jquery.dataTables 1.10.16 version. And I am using jquery.dataTables 1.9.4.
Can the same functionality as listed in example given above be possible with jquery.dataTables 1.9.4 instead of jquery.dataTables 1.10.16?
In the same page which you give the link, there are many explanation about to using "single check" oparetion.
At the end of the listed attachment, you can see the referanced .js file is
https://cdn.datatables.net/select/1.2.5/js/dataTables.select.min.js
In your page, you should add this file referance after dataTable.js.
I think, the version of jquery is not important. The important file is "dataTables.select.js"!
Secondly, you must update your dataTable maker codes like the sample below;
$(document).ready(function() {
$('#example').DataTable( {
columnDefs: [ {
orderable: false,
className: 'select-checkbox',
targets: 0
} ],
select: {
style: 'os',
selector: 'td:first-child' // this line is the most importan!
},
order: [[ 1, 'asc' ]]
} );
} );
UPDATES :
Why dont you try to write your own selector function?
for example;
$(document).ready(function() {
$('#example').DataTable( {
/// put your options here...
} );
$('#example').find("tr").click(function(){ CheckTheRow(this); });
} );
function CheckTheRow(tr){
if($(tr).find("td:first").hasClass("selected")) return;
// get the pagination row count
var activePaginationSelected = $("#example_length").find("select").val();
// show all rows
$("#example_length").find("select").val(-1).trigger("change");
// remove the previous selection mark
$("#example").find("tr").each(function(i,a){
$(a).find("td:first").removeClass("selected");
$(a).find("td:first").html("");
});
// mark the picked row
$(tr).find("td:first").addClass("selected");
$(tr).find("td:first").html("<i class='fa fa-check'></i>");
// re turn the pagination to first stuation
$("#example_length").find("select")
.val(activePaginationSelected).trigger("change");
}
Unfortunately, legacy data table does not support or have that select extension.
Workaround:
Create checkbox element inside 'mRender' callback.
Bind action to the checkbox. (This can be done inside the fnRowCallback or outside as in my example in below fiddle
https://jsfiddle.net/Rohith_KP/dwcatt9n/1/
$(document).ready(function() {
var userData = [
["1", "Email", "Full Name", "Member"],
["2", "Email", "Full Name", "Member"]
];
var table = $('#example').DataTable({
'data': userData,
'columnDefs': [{
'targets': 0,
'className': 'dt-body-center',
'mRender': function(data, type, full, meta) {
return '<input type="checkbox" value="' + $('<div/>').text(data).html() + '">';
}
}],
'order': [1, 'asc']
});
$('#example tr').click(function() {
if ($(this).hasClass('row_selected'))
$(this).removeClass('row_selected');
else
$(this).addClass('row_selected');
});
});
Also, I suggest you to upgrade your datatable version. Then you can use that select extension.
Can the same functionality as listed in example given above be possible with jquery.dataTables 1.9.4 instead of jquery.dataTables 1.10.16?
Yes.
But, not using the Select Extension since it requires at least version 1.10.7.
For 1.9.4, a possible solution would be:
$(document).ready(function() {
$('#example').find("td input[type='checkbox']").click(function() {
selectRow(this);
});
var table = $('#example').DataTable();
function selectRow(clickedCheckBox) {
var currentPage = table.fnPagingInfo().iPage;
// Being unchecked
if (!$(clickedCheckBox).is(':checked')) {
$(clickedCheckBox).removeAttr('checked');
getRow(clickedCheckBox).removeClass('selected');
return;
}
var selectEntries = $("#example_length").find("select");
var showEntriesCount = selectEntries.val();
var totalRows = table.fnGetData().length;
// If show entries != totalRows append total rows opiton that can be selected
if (totalRows != showEntriesCount)
selectEntries.append($('<option>', {
value: totalRows,
text: totalRows
}));
// Display all rows
selectEntries.val(totalRows).trigger("change");
// Removes all checked attribute from all the rows
$("#example").find("td input[type='checkbox']").each(function(value, key) {
getRow(key).removeClass('selected');
$(key).removeAttr('checked');
});
// Check the clicked checkBox
$(clickedCheckBox).prop('checked', true);
getRow(clickedCheckBox).addClass('selected');
// Re set the show entries count
selectEntries.val(showEntriesCount).trigger("change");
// If added, Remove the additional option added to Show Entries
if (totalRows != showEntriesCount)
selectEntries.find("[value='" + totalRows + "']").remove();
// Go to the page on which the checkbox was clicked
table.fnPageChange(currentPage);
}
function getRow(element) {
return $(element).parent().parent();
}
});
The above will require fnPagingInfo to take the user back to initial page. I haven't tested the solution on large dataset, tested it on a table with 150 rows, but should work fine on larger datasets too.
JSFiddle
Have you tried below code and I checked and it is working fine, you need to update styles and scripts:
You havr to update the latest styles and scripts to achieve latest functionality.
Single check box selection with jquery datatable
It looks like a simple task, but I already spent 4 hours to find a solution. How can I highlight the entire row by cell click?
On register api I have next
$scope.gridOptions.onRegisterApi = function(gridApi){
$scope.gridApi = gridApi;
gridApi.cellNav.on.navigate($scope,function(selected){
if('.ui-grid-cell-focus '){
console.log("fired class")
$(selected.row.entity).addClass('ui-grid-cell-focus')
}
console.log("fired cell")
$(selected.row.entity).addClass('ui-grid-cell-focus')
});
};
I see how click on cell is fired, but I cannot force to color the row and I don't want to select the row, because I use check box selection for this purpose, I just want to highlight the row by click on any cell in this row. Could somebody tell me where my mistake is?
Attached plunker
One way to accomplish what you want is to add a cellClass definition to your columnDefs. That function takes two params: grid and row.
$scope.gridOptions.columnDefs = [{
name: 'id',
width: '150',
cellTemplate: "",
cellClass: getCellClass
}, {
name: 'name',
width: '200',
cellClass: getCellClass
} ...
];
function getCellClass(grid, row) {
return row.uid === selectedRow ? 'highlight' : '';
}
On click you could set a variable to the uid of the row, and inside the cellClass function you can check if the uid of the current row matches the uid of the selected, if so, you can set the class to a class that properly reflects the background color of the selected row.
var selectedRow = null;
gridApi.cellNav.on.navigate($scope, function(selected) {
if ('.ui-grid-cell-focus ') {
selectedRow = selected.row.uid;
gridApi.core.notifyDataChange(uiGridConstants.dataChange.COLUMN);
}
});
Here's a link to your updated plunker: http://plnkr.co/edit/AgpAI2cmdqgNsSLVNjYA?p=preview
If you don't like the cellClass approach you could define custom cellTemplates and similarly react to a property you set on the row entity.
I do have a php generated page, with a table that exists after the page loaded.
<table id="#previewTable">
<thead>
<th class="colA">column a - Firstname</th>
<th>column b - Lastname</th>
</thead>
<tbody>
<tr>
<td class="colA">Alexander
</td>
<td class="colB">Zandvoort
</td>
</tr>
<tr>
<td class="colA">Alexander
</td>
<td class="colB">Brno
</td>
</tr>
<tr>
<td class="colA">Bastian
</td>
<td class="colB">Zolder
</td>
</tr>
</tbody>
</table>
During doc.ready I apply the tablesorter widget like so:
var the_table = $('#previewTable');
//the_wrapper ==> any jquery selector (not object!) like '.mywrapper' or '#mywrapper'
//the_table ==> any jquery selector (not object!) like '.mytable' or '#mytable'
//the_childs_class ==> class name of the chilkd rows, like 'child-row' - NO dot!
var idx = $(the_table+'.ts-date').index(); //all headers with german dates
var options = {
showProcessing: true,
sortReset : true,
saveSortReset : false,
resort:true,
widgets: [ 'saveSort','zebra','stickyHeaders' ],
cssInfoBlock : "row-sorter-false",
//those rows will NOT be included in a sorting! useful to implement blockwise sorting
widgetOptions: {
// number or jquery selector targeting the position:fixed element
stickyHeaders_offset : 0,
// added to table ID, if it exists
stickyHeaders_cloneId : '-sticky',
// trigger "resize" event on headers
stickyHeaders_addResizeEvent : true,
// if false and a caption exist, it won't be included in the sticky header
stickyHeaders_includeCaption : true,
// scroll table top into view after filtering
stickyHeaders_filteredToTop: true,
/* make the table scroll within its wrapper */
stickyHeaders_attachTo : the_wrapper
},
cssChildRow: the_childs_class,
dateFormat : "ddmmyyyy", // set the default date format
idx: { sorter: "shortDate", dateFormat: "ddmmyyyy" }
};
$(the_table).tablesorter(options);
After that has been done everything is fine.
Now the users will sort any two of the let's say ten columns A and B in whatever direction.
The saveSort widget remembers everything pretty fine.
We do have a checkbox for each column "hide that column".
Un/checking that checkbox for let's say B should hide/show the according column B, remove the sorting of the rows that has been done through column B and reapply any existing remaining sorting - in this case A.
I tried doing that like so:
$(document).on('click','.chk_must',function(){ //all checkboxes in MUST
theSortList = $( '#previewTable' ).get(0).config.sortList;
var new_sort_list = [];
if($('.chk_must_'+$(this).attr('data-nr')).is(':visible')){
$('.chk_must_'+$(this).attr('data-nr')).hide();//show or hide M1 and so on rows
theColumnNumber = $('.chk_must_'+$(this).attr('data-nr')).attr('data-column');
$(theSortList).each(function(key,element){ //get the header text for each selected
//var element[0] // var element[1]; //[0]=field number starting at 0, [1]=sort order, whereas 0=ASC and 1=DESC
if(element[0]!=theColumnNumber){
new_sort_list.push(element);
}
});
if (new_sort_list.length==0){
//nothing
}else{
$( '#previewTable' ).get(0).config.sortList = [new_sort_list];
$('#previewTable').trigger( 'sorton',[new_sort_list] );
}
$("#previewTable").trigger("updateCache").trigger("updateAll");
$('#previewTable').trigger('refreshWidgets', true,false);
}else{
$('.chk_must_'+$(this).attr('data-nr')).show();//show or hide M1 and so on rows
}
});
What ever I do....the sort is not going to be reseted and redone according to [new_sort_list]but stay the same. Hiding/Showing of the column itselfs works as well.
It seems like I'm not applying the correct type /format of new_sort_list and that may be the internal cache is not going to be reseted - even not with refreshWidgets and updateCache and all that.
Any ideas what could be done to get this to work?
TIA
Alex
First off, remove the triggers for updateCache & updateAll. They aren't needed when only sorting is involved.
The values in sortList consist of a column index, and sort direction grouped together. For example:
// [ [ columnA, direction ], [ columnB, direction ] ]
table.config.sortList = [ [0,0], [1,0] ];
So, the code above has this function:
$(theSortList).each(function(key,element){ //get the header text for each selected
//var element[0] // var element[1]; //[0]=field number starting at 0, [1]=sort order, whereas 0=ASC and 1=DESC
if(element[0]!=theColumnNumber){
new_sort_list.push(element);
}
});
This function should be using jQuery.each() and not the each function above which is used for DOM elements.
Maybe instead, if there are only a few columns, you can pick primary columns and sort that one when the others are hidden.
Here is some untested code as an example:
var direction = 'asc', // use 'desc' for descending sort
// sort column priority from left-to-right
priorities = [ 0, 1, 2, 3 ],
config = $( '#previewTable' ).get(0).config,
sortColumn = -1,
theColumnNumber = $('.chk_must_'+$(this).attr('data-nr')).attr('data-column');
$.each( priorities, function(indx, val) {
// config.$headerIndexed sets one header cell for each column
// in a basic array (not a jQuery object set); it is
// needed for tables with multiple thead rows & colspans
if ( !config.$headerIndexed[ val ].is(':hidden') ) {
sortColumn = val;
break;
}
});
if ( sortColumn > -1 ) {
$( '#previewTable' ).trigger('sorton', [ [[ sortColumn, direction ]] ]);
}
Or, you could use the columnSelector widget to do the work of hiding & showing columns. And add this very basic code (only written for 2 columns) which updates the sort when the columns change visibility (demo):
$(function () {
/*** custom css only button popup ***/
$('table').tablesorter({
theme: 'blue',
widgets: ['zebra', 'columnSelector', 'stickyHeaders'],
widgetOptions: {
columnSelector_container: $('#columnSelector'),
columnSelector_mediaquery: false
}
}).on('columnUpdate', function(){
var sortCol = 0,
s = this.config.selector;
// if column a is hidden & column b is showing
// sort column b
if ( !s.states[0] && s.states[1] ) {
sortCol = 1;
}
$(this).trigger('sorton', [ [[sortCol, 0]] ]);
});
});