I have a table which is updated with ajax and after update it if sorted but I need to sort not a fixed column but the same column which was last clicked before update.
function tableUpdated() {
$(".tablesorter").trigger("update");
//alert($(".tablesorter").sorting);
var sorting = [[7, 0]];
$("table").trigger("sorton", [sorting]);
}
In my code above I need to put my selected column index instead of 7
jQuery's .data() will help you here. Whenever the user clicks to sort a table, store the columns on the table itself. Within the sort function, add this:
$("#table").data('sorting', selectedColumn);
Now the element with id="table" has a property sorting with the value of selectedColumn. In tableUpdated, you can use this data:
function tableUpdated() {
$(".tablesorter").trigger("update");
var sorting = [[$("#table").data('sorting'), 0]];
$("#table").trigger("sorton", [sorting]);
}
Data added using .data() can be even more complex, allowing you to add objects of data. See this page for more details.
Using your code, you can do something like this (suppose your table id is #list-table) to maintain current table sorting:
function tableUpdated() {
$("#list-table").trigger("update");
var sorting = $("#list-table").get(0).config.sortList;
$("#list-table").trigger("sorton", [sorting]);
}
you can pick it up on the 'sortEnd' event on your table:
var lastSortList;
$table.on('sortEnd', function(e) {
lastSortList = e.target.config.sortList;
});
After battling with this for a day or so I found the datatables plugin which has state saving out of the box. I hope this helps someone else.
Here you can order with the same column and add a new one to sorter
var sorting = $("table").get(0).config.sortList;
sorting.push([2,0]); // add an element to the array
$("table").trigger("sorton", [sorting]);
It might a bit less overhead to save the last sort only when starting ajax like this:
lastSortList=$("table")[0].config.sortList;
Then get it back in after update like this:
$("table").trigger("sorton", [lastSortList]);
Remember to declare the first line in the right scope though.
Related
I have jqGrid parent and another jqGrid child in a popup dialoag. The parent jqGrid has already a set of records in it and whenever I add new set of records from child jqGrid to parent jqGrid, I am losing the existing data from the parent jqGrid.
I tried the following.
concat the data from the parent to the child and then set it to the parent jqGrid.
var gridParent = jQuery("#parentGrid");
var existingRowsInParentGrid = gridParent.jqGrid('getGridParam','data');
var gridChild = jQuery("#childGrid");
var newRowsInChildGrid = gridChild .jqGrid('getGridParam','data');
var json = existingRowsInParentGrid.concat(newRowsInChildGrid );
//set the new concatnated data to parent
gridParent.jqGrid('setGridParam', {data: json}).trigger('reloadGrid');
Tried to use
Object.assign(existingRowsInParentGrid, newRowsInChildGrid)
Tried to use the extend feature.
var sum = jQuery.extend(existingRowsInParentGrid, newRowsInChildGrid );
It simply replaces the existing records with the new set of records. I am not adding records one at a time but setting the data in bulk. Does this make the difference?
I see lots of code, which tells me to add one record at a time. I was hoping that there will one way where we just need to add the whole set of new records at the end of the existing records.
Since you do not post the configuration of both grids it is difficult to help.
In most cases it is better to read the up to date documentation, rather than to read some posts. If you do not know addRowData can add multiple rows at once.
For more info refer the docs here (search for addRowData method)
Thanks, Tony.
I've found the solution after doing trial and error. Below is what I did which worked for me, perhaps it might help someone else!
Find the number of rows from the first jqGrid.
var existingRowsInParentGrid = gridParent.jqGrid('getGridParam','data');
var noOfRowsInParentGrid = existingRowsInParentGrid.length;
Find the number of rows from the second jqGrid.
var noOfRowsInChildGrid = gridChild.length;
Iterate through the 2nd grid elements and add rows to the parent grid at the correct position.
for(var i = 0;i < noOfRowsInChildGrid; i++) {
gridParent.jqGrid('addRowData', noOfRowsInParentGrid +1 , gridChild[i]);
noOfRowsInParentGrid = noOfRowsInParentGrid + 1;
}
My initial intention of loading the data in bulk still did not work though. But for now, I am happy as I will not have a huge amount of data in 2nd grid.
I am using an amazing tabulator plugin for managing tabular data, API is very clear and reliable but i cant do a very simple thing: get/select all rows on current page.
Custom row selection can look like this:
table.selectRow(table.getRows().filter(row => <<Custom Selection>>);
Where Custom selection has to respect the current page, but i dont get from where i can take it.
Maybe i am missing something?
There is no way to do that directly form Tabulator, but is should be fairly easy to do yourself with a bit of JavaScript.
First you want to get the rows that are visible on that page:
var pageRows = table.getRows(true);
Then you want to get the selected rows
var selectedRows = table.getSelectedRows();
then you want to find rows that exist in both arrays, these will be the selected rows on that page:
var rows = selectedRows.filter(value => -1 !== pageRows.indexOf(value));
Assuming the column name of your index is 'id' you can do the following:
var selectedData = table.getSelectedData();
jQuery.map(selectedData, function(value, index) {
console.log(value.id);
});
I've got datatables set up nicely and with the select extension - I have this code for when someone uses a "report" and it loads another page using some cell content from the table to pass to the report. That works fine, however - I need to be able to pass a data-element of each <tr> of the table instead of the row data...
This is my current code:
var table = $('#table_search_project').DataTable();
//then re-run the code to get the selected rows
var id_list = $.map(table.rows('.selected').data(), function (item) {
return item[1]
});
So you can see, I used to use item[1] to return, but I really want to be able to get the <tr> object so I can retrieve the data-something-id property (but I don't want to show it - hence the issue)
I worked it out. Too hasty to ask in SO!
I used this instead:
var id_list = $.map(table.rows('.selected').nodes(), function (item) {
return $(item).data("entity-id");
});
The nodes() collection sends me back the <tr> elements instead of the data. Exactly what I wanted. Found the information here:
https://datatables.net/reference/api/row().node()
Using DataTables 1.10,
I have a DataTable with a default sort and the user can resort by some of the other columns.
How do I detect the column by which the table is currently sorted?
Some context which may not be relevant to answering the question: What I'm really trying to do is "export" the table to a non-interactive HTML table. This DataTable is generated programmatically and then turned into a DataTable, so after some searching for export options it looks like it will be easier to essentially regenerate the original table than to actually export. But I need the regenerated table to have the rows in the same order as the current sort.
The current sort state sortInfo can be retrieved like this:
var apiObject = $("#myPlainTable).DataTable( dtOptions );
// ...
var sortInfo = apiObject.settings().order()
More specifically, the column and direction are encoded like this:
var sortCol = sortInfo[0][0]; // counting from left, starting with 0
var sortDir = sortInfo[0][1]; // either "asc" or "desc"
Caveats:
The sortInfo object will have the above format after the user changes the sorting; if you specify the initial sort by setting dtOptions.order using a different format, then the sortInfo object will have the original value you specified until the user changes the sorting. (For example, DataTables will accept [1,'asc'] in addition to the above [[1,'asc']]; I didn't test what happens if you pass a value DataTables can't use.)
This describes the default case where you sort by one column only, not using the multi-column sort feature.
When you are using dataTables 1.10.x already, why not use the API? By that it is easy :
table.rows().data()
returns an array of arrays containing the current content of the table, i.e the rows as they are currently sorted. So if you want to export or clone the content of a dataTable to a static table, you can actually do it very simple :
$("#clone").click(function() {
var cloneTable = '';
table.rows().data().each(function(row) {
cloneTable += '<tr><td>' + row.join('</td><td>') + '</td></tr>';
})
$('#cloneTable tbody').html(cloneTable);
})
demo -> http://jsfiddle.net/zuxm2e68/
If sending to the server you check the
order[i][column]
order[i][dir]
for column and direction. See here
Since you are using 1.10, you can use the following:
var table = $('.myTable').dataTable({ /* Your options */ });
var sortArray = table.api().settings().aaSorting; // gives array
If you are using API already via $('.myTable').DataTable({...}), you can omit the .api().
I'm using SlickGrid with DataView and I'm trying to set a default sort column on my table. Is there a way to trigger the sort or set an option so the column is sorted on load?
On the latest version you could do this:
grid.setSortColumn("myColId",true); //columnId, ascending
You can also set multiple with setSortColumn*s*
See my solution here. This applies sort on a column initially without using Dataview.
Calling sort on slickgrid
I think it does what you want.
Btw since you are using Dataview. You can also give this a try. But I have not personally tried this.
dataview.reSort()
I had an interesting thought which worked, and that was to just enable the multi-column header sorting (example-multi-column-sort.html), and then once the grid was loaded simulate a click() on the header row I wanted to be sorted when the grid first appeared ("time" is the name of my column I was sorting). The ID of the column headers is calculated similar to the id for the root div of the grid (at least for now :0) ):
var gridId = $('#myGrid').attr("class");
gridId = '#'+gridId.replace(" ui-widget","")+'time';
$(gridId).click();
The user then can click whatever other column headers they want, but I just clicked the first one for them.
This ended up being my solution just give slick grid the data in the way you want it sorted. then let multisort handle it the rest of the time. still doesn't sold programmatically setting the sort and having the grid update but its quick and easy
this.data = res.data.sort((a, b) => {
let x = a[config.sortField], y = b[config.sortField];
return (x == y ? 0 : (x > y ? 1 : -1));//no ===
})