DataTables selected rows data-attribute - javascript

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()

Related

When adding new data/rows to a one jqGrid1 from another jqGrid2, the old data in jqGrid1 is lost (javascript)

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.

Tabulator.js: get/select rows on current page

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);
});

Setting the row order of tr tags

Wondering if there is a attribute for the tr tag that you can set that determines which order it will render on the webpage in.
I have code that dynamically creates a table based on an array, in this array there is also a piece of data that says which order each row is in, but the data comes in arbitrarily.
Take this example:
<table>
<tr row="0">A</tr>
<tr row="2">C</tr>
<tr row="1">B</tr>
<table>
The table would be structured this way in the dom structure, but when rendered i'd like it to show up like this:
<table>
<tr row="0">A</tr>
<tr row="1">B</tr>
<tr row="2">C</tr>
<table>
If this row attribute or anything similar doesn't exist can I do it with JavaScript?
I have code that dynamically creates a table based on an array
You should sort the array in the order that you want before you build the table.
For example, to sort by a property called "index":
myArray.sort(function(a, b) {
return +(a.index > b.index);
})
If your source data is complex you could define a separate function that returns the property that should ultimately be used to sort the table:
function getSortKey(element) {
// write the logic to return your "row" attribute. It can be
// as complex as necessary (but it must be synchronous).
// a made-up example:
return element.members ?
? element.members[0].name
: element.defaultName ;
}
myArray.sort(function(a, b) {
return +(getSortKey(a) > getSortKey(b));
})
There isn't a built-in way to change the order that rows are rendering in, and changing the order with JavaScript after rendering is inefficient.
This is something you should probably fix from higher up before the table is parsed to the DOM, but something along these lines could work (fyi no time to debug it right now)
var table_tr = [];
jQuery("#mytable").find("tr").each(function(){
table_tr[parseInt(jQuery(this).attr("row"))] = jQuery(this).clone(true,true);
jQuery(this).remove();
});
jQuery.each(table_tr,function(index,element){
jQuery("#mytable").append(element);
});
EDIT:
Kinda ugly, but it works:
https://jsfiddle.net/ezbd9huv/
Seriously though, you should consider fixing it before it prints to the DOM~

SQLite: issue with SELECT * FROM Tble where?

I am working offline with SQLite, Javascript and Chrome
In my main page (main.html), I have two div: <div id="menuLeft"> that contains the list of items name with buttons to edit each item, and
<div id="content">
The list of item is written as follows:
<li>ItemName1
<div id="idItem1" class="editItem_btn">
<img src="btn_edit.png">`
</div>
</li>
In main.html, I have the following code:
$("#menuLeft").delegate(".editItem_btn", "click", function(e0)
{
e0.preventDefault();
var editItemId = $(this).attr("id");
editItemId = parseInt(editItemId);
var url="edititem.html"
$("#content").load(url,function(){
loadRecord(editItemId);`
});
});
When I click on the edit button of a given Item, the id of the Item is first retrieved from the id of the div around the edit button. Then I load the page edititem.html content. On success, I run the function loadRecord(editItemId), where loadRecord(i) is contained in edititem.html:
function loadRecord(j)
{
var item = dataset.item(j);
idItem.value = item['id'];
ItemName.value = item['ItemName'];
dateStart.value = item['dateStart'];
dateEnd.value = item['dateEnd'];
notes.value = item['notes'];
}
This function enables to display the parameters of Item (id, ItemName....) contained in the database.
Here is my problem, the code works but in a weird way meaning that if I click on the edit button of Item1, the parameters of Item2 are displayed. Same thing if I click on edit Item2, parameters of Item3 are displayed.
I then replaced:
var item = dataset.item(j);
with:
var item = dataset.item(j-1);
and that works. But I need to understand why it's behaving like that, and why I need to use (j-1). I placed some alert() in the jquery code to check that I have the right editItemId number, and in the function loadRecord(j). The right id number is retrieved after the click and the right id number is passed to the function. I have no idea what's the bug here!
Without seeing the sql side of things, and how that data is passed back to your script it's impossible to tell you exactly what's happening, but this is simply a case of some lists being 0 based and some lists being 1 based. For example, arrays are generally 0 based (unless you specifically create them a different way), but $("#id").each(function(Index)... is 1 based. You just have to know what you're working with and occasionally do as you have found and use -1 or +1 when relevant.
While I'm not familiar with the intricacies of SQLite, I suspect that dataset.item(j):
is accepting a 0-based index
that you are passing in the record_id (which in itself is not actually an array index)
and that the record_id for the dataset you are testing just happens to be the index + 1 (meaning you're getting lucky right now and that it will probably change when the next dataset is loaded).
I would check to see if there's an equivalent for dataset.item(j) which accepts a record_id and not an index. Otherwise, you'll probably want to store the index of the record somewhere in the record itself to be able to pass it to your loadRecord function.
Hope this helps,
Pete

Jquery Tablesorter sort same column after update

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.

Categories