Two DataTable in One Page - Second one initialising weird - javascript

I have two dataTable in my page and I have a method like below:
function ToDataTable()
{
$(".dataTable").css("width", "100%");
$(".dataTable").each(function ()
{
var $that = $(this);
/* Start of method */
function ToDataTableInternal()
{
var table = $that.DataTable({
responsive: {
details: { type: "column", target: -1 },
},
columnDefs: [{
className: "control", orderable: !1, targets: -1,
},
{ orderable: !1 }],
"paging": false,
"ordering": false,
"info": false,
"searching": false,
retrieve: true
});
}
/* End of method */
if ($that.is(":visible"))
{
ToDataTableInternal()
}
else
{
// Observe all invisible parents or table to trigger
// ToDataTableInternal method if made visible
var $arr = $(this).parentsUntil(":visible").filter(function ()
{
return $(this).css("display") === "none";
}).add($(this));
var observers = [];
$arr.each(function ()
{
var observer = new MutationObserver(function (mutations)
{
mutations.forEach(function (mutation)
{
if ((mutation.attributeName === 'style' ||
mutation.attributeName === 'class') &&
$that.is(":visible"))
{
ToDataTableInternal();
for (var i = 0; i < observers.length; i++)
{
// Disconnect observers
observers[i].disconnect();
}
}
});
});
observers.push(observer);
observer.observe(this, {
attributes: true
});
});
}
});
}
The reason I have this method is that when table's display is none, it really lags browser(especially IE, where I cannot do anything for minimum of 5 seconds) which is the reason of that I'm changing the table to DataTable after it made visible.
But the problem with calling methods individually is the second DataTable doesn't have the same settings which I passed on.(The first one has) Instead, second one has filters, paging, sort elements in it too.
If I call both at the same time, nothing out of ordinary happens. What may be the problem?
EDIT: I can't reproduce the same behaviour in fiddles.

There seems to be no problems in another environments when I'm trying to do the same thing.
An another library we use is causing problems and there is no problem with DataTable library.

you can add following properties of dataTable in your datatable configuration to remove filtering, pageing and sorting:
Datatable 1.9
"bPaginate":false, //Enable or disable pagination.
"bFilter": false, //Enable or disable filtering of data
"bLengthChange": false, //Enable or disable the size dropdown
"bSort": false, //Enable or disable sorting of columns.
"bInfo": false, //Enable or disable the table information display.
Update
Datatable 1.10
Option name update in datatable 1.10
bPaginate -> paging
bFilter -> searching
bLengthChange -> lengthChange
bSort -> ordering
bInfo -> info

Related

jQuery DataTables checkboxes extension can not retrive selected data correctly at IE browser

I use jQuery datatables checkboxes extension to give my table multi select function. When any row's checkbox is clicked, I retrieve all the selected rows' first cell's data send to server.
The code works in Chrome browser, but does not work in IE browser.
$(document).ready(function () {
var table = $('#tbl_inv').DataTable({
"paging": false,
//"ordering": false,
"info": false,
"searching": false,
'columnDefs': [
{
'targets': 0,
'checkboxes': {
'selectRow': true
}
}
],
'select': {
'style': 'multi'
},
'order': [[1, 'asc']]
});
$('#tbl_inv input[type="checkbox"]').on('change', function () {
$.ajax({
url: '/Invoices/Pickup?handler=CalcTotaltoPay',
data: {
invIds: $('#tbl_inv').DataTable().column(0).checkboxes.selected().join(),
clientId:1234
}
})
.done(function (result) {
freshResult(result);
});
// Iterate over all selected checkboxes
//$.each(table.column(0).checkboxes.selected(), function (index, rowId) {
// console.log(index + '---' + rowId)
// console.log(table.cell(index, 5).data())
//});
});
});
When I use IE browser, .column(0).checkboxes.selected() returns a list, this list not include current clicked checkbox state change. meaning, when checkbox checked, .column(0).checkboxes.selected() return a list not include current checkbox's data. when checkbox unchecked, .column(0).checkboxes.selected() return a list still include this checkbox's data.
This is due to the racing condition with jQuery DataTables Checkboxes plug-in. It handles change event internally to update the list of selected checkboxes. When you handle change event yourself, apparently in IE plug-in is still unaware of the change.
Try using columns.checkboxes.selectCallback option for handling event when state of the checkbox changes.
'columnDefs': [
{
'targets': 0,
'checkboxes': {
'selectRow': true,
'selectCallback': function(nodes, selected){
// Handle checkbox state change event
}
}
}
],

How to remove sorting on ui-grid before reload another data set ui-grid

Im using ui-grid to load my data set. Here is my requirment;
step 01: I want to load dataset_01 (scope.gridOptions.data = res_01;).
step 02: I want to sort by First Name (Click by firstname column).
step 03: Click an external button and Reload ui-grid with an another data set (scope.gridOptions.data = res_02;).
Here is my result:
I dont want sort by First Name here for second dataset.
I want data without sorting. How can I do it ?
Expected result:
So I want to reload second data set without sorting (Means I want to remove first sorting before load second data set). how can I reset my ui-grid before load next data set (scope.gridOptions.data = res_01;).
How can I do it ?
Thank you. :)
You can set the sort property of your columnDefs to:
sort: {
direction: undefined,
}
and call for grid refresh using $sope.gridApi.core.refresh() after. This should re-render the whole grid and get rid of the sorting.
Visit this page: http://ui-grid.info/docs/#/api/ui.grid.core.api:PublicApi
After having instantiated your gridApi, you can just call:
$scope.gridApi.core.refresh();
Hope that helps! :)
Create your gridoption like this
example
$scope.gridOptions = {
useExternalPagination: true,
useExternalSorting: false,
enableFiltering: false,
enableSorting: true,
enableRowSelection: false,
enableSelectAll: false,
enableGridMenu: true,
enableFullRowSelection: false,
enableRowSelection: false,
enableRowHeaderSelection: false,
paginationPageSize: 10,
enablePaginationControls: false,
enableRowHashing: false,
paginationCurrentPage:1,
columnDefs: [
{ name: "FristName", displayName: "Frist Name", width: '6%', sort: { direction: undefined } },
]
};
after that you can remove the sorting where you want using below code
$scope.RemoveSorting = function ()
{
$scope.gridOptions.columnDefs.forEach(function (d) {
d.sort.direction = undefined;
})
}

Storing state using 2 instances of the same JQuery plugin

I'm coding a jQuery plugin to build KendoUI grids. Everything was fine until I had to use 2 instances of the plugin in the same page. In this case, I need each instance of the plugin to have its own data.
I've read the jQuery guidelines for storing data with .data(), but when trying to access from outside the code of the plugin to the 'getSelectedItem()' this way:
selectedItemGrid1= $("#Grid1").kendoGrid_extended.getSelectedItem();
selectedItemGrid2= $("#Grid2").kendoGrid_extended.getSelectedItem();
I get the selectedItem of Grid2 in selectedItemGrid1. Here is a simplified version of my plugin code. Basically what I wanted to do is, anytime a row of the grid is selected ("change" event on the kendoGrid definition), store the new selected row inside the plugin, so when the user clicks on a "delete" button, read from the plugin the selected row and call the delete action with the info recovered from the plugin.
$.fn.kendoGrid_extended = function (options) {
var opts = $.extend({}, $.fn.kendoGrid_extended.defaults, options);
opts.controlId = '#' + this.attr('id');
var gridExtended;
var selectedItem;
var instance = $(this);
//Public accessor for the selectedItem object.
$.fn.kendoGrid_extended.getSelectedItem = function () {
return instance.data('selectedItem');
}
opts.gridDataSource = new kendo.data.DataSource({
type: "json",
serverPaging: true,
serverSorting: true,
sort: sortObject,
serverFiltering: true,
allowUnsort: true,
pageSize: opts.pageSize,
group: opts.group,
transport: {
read: {
url: opts.dataSourceURL,
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: function () { return opts.dataSourceParamsFunction(); }
},
parameterMap: function (options) {
return JSON.stringify(options);
}
},
schema: opts.dataSourceSchema,
});
gridExtended = $(opts.controlId).kendoGrid({
columns: opts.gridColumns,
dataSource: opts.gridDataSource,
pageable: {
refresh: true,
pageSizes: true
},
groupable: opts.groupable,
sortable: { mode: "multiple" },
filterable: false,
selectable: true,
scrollable: true,
resizable: true,
reorderable: true,
columnReorder: SetColumnsReorder,
columnResize: SetColumnsResize,
change: function () {
var gridChange = this;
gridChange.select().each(function () {
selectedItem = gridChange.dataItem($(this));
instance.data('selectedItem', selectedItem);
});
}
});
}
The code itself it's a simplified version of my plugin. I know that this may not be the best way to write a plugin as I've read the jQuery guidelines for plugin development. It would be awesome if you could point me in the right direction or tell me why my code is not working. Thanks a lot in advance!
I think you do not need that "public accessor" that you wrote, I think you actually can get it like this:
selectedItemGrid1= $("#Grid1").data('selectedItem);
selectedItemGrid2= $("#Grid2").data('selectedItem);
On a side you do not have to wrap that instance element into a jQuery object. You still be able to use rest of the jQuery methods, check the example.
I finally solved it appending a hidden input with a unique Id to the grid of the helper. On that hidden input I'm storing all the data that I want to be persistent with the Jquery .data().
So if I generate 2 grids using the plugin, each grid will have appended something like this:
<input type="hidden" id="uniqueIdHere" />

Call custom method on keypress SlickGrid

I am using slickgrid to display certain data. How can i add custom method to slickgrid rows ?
For eg: I want to open modal box with current row data whenever enter key is pressed.
You can subscribe to the onKeyDown event in the grid to check this. Something like:
grid.onKeyDown.subscribe(function(e) {
if (e.which == 13) {
// open modal window
}
});
Let me know if this helps!
If i got your requirement well, then try out this code,
createInvoiceDetailsTable : function () {
var gridOptions, gridColumns;
gridColumns = [
{id:'ean_code', name:'EAN', field:'ean_code', width:125, cssClass: 'grid-cell'},
{id:'description', name:'Product Description', field:'description', width:250, formatter:opr.invoice.productGridDescriptionFormatter, cssClass: 'grid-cell'},
{id:'qty', name:'Qty', field:'qty', width:40, , formatter:UpdateQtyBtnFormatter},
];
gridOptions = {
editable: true,
autoEdit: true,
enableAddRow: false,
enableCellNavigation: true,
asyncEditorLoading: false,
enableColumnReorder: false,
rowHeight: 35
};
dataView = new Slick.Data.DataView();
invoiceProductGrid = new Slick.Grid($('#invoice_details_grid_div'), dataView , gridColumns, gridOptions);
function UpdateQtyBtnFormatter (row, cell, value, columnDef, dataContext) {
return '<input type="button" style="width:30px; height:30px;" class="update_invoice_product_qty" id="' + value + '" value="Q"/>';
}
}
Using this update_invoice_product_qty class name you can write event.
If this is not your requirement then please share with some code or procedure which you tried earlier.

Flexigrid: selection of rows to survive refresh

I am using flexigrid in a project and I would like to be able to keep the selected rows after the grid is refreshing. I asked the same question on the flexigrid discussion board and I got this answer:
Add a click handler, save the id if the row id of the row selected. On refresh completion, select the row again (if still present)
Not sure how to proceed on this, I don't even know how a function will look like, so that's why I don't have any code to start with.
If someone could point me in the right direction will be greatly appreciated.
Thanks,
Cristian.
Flexigrid adds a class called trSelected to selected rows, so whenever a click event happens on the grid you could just look for all the selected rows and save them in some way. Below is just a quick example of what you could do:
var selectedRows = new Array();
$('#myGrid').click(function() {
selectedRows = new Array();
$(this).find('tr.trSelected').each(function(i, selectedRow) {
selectedRows.push($(selectedRow));
});
});
I have done small code to keep multi-selection between pagination and also during refresh.
$("#searchPhonoList").flexigrid($.extend({}, flexigridAttrs, {
url: './rest/phono/search',
preProcess: formatSearchPhonoResults,
onSuccess: successSearchPhono,
onSubmit: submit,
method: 'GET',
dataType: 'json',
colModel : [
{display: 'titre', name: 'titre_brut', width : 240, sortable : true, align: 'left'},
{display: 'version', name: 'version_brut', width : 60, sortable : true, align: 'left'}
],
height: "auto",
sortname: "score",
sortorder: "desc",
showTableToggleBtn: false,
showToggleBtn: false,
singleSelect: false,
onToggleCol: false,
usepager: true,
title: "Liste des candidats",
resizable: true,
rp:20,
useRp: true
}));
var searchPhonoListSelection = new Array();
$('#searchPhonoList').click(function(event){
$(' tbody tr', this).each( function(){
var id = $(this).attr('id').substr(3);
if ( searchPhonoListSelection.indexOf(id) != -1 ) {
searchPhonoListSelection.splice(searchPhonoListSelection.indexOf(id), 1);
}
});
$('.trSelected', this).each( function(){
var id = $(this).attr('id').substr(3);
if ( searchPhonoListSelection.indexOf(id) == -1 ) {
searchPhonoListSelection.push(id);
}
});
});
function successSearchPhono() {
$("#searchPhonoList tbody tr").each( function() {
var id = $(this).attr('id').substr(3);
if ( searchPhonoListSelection.indexOf(id) != -1 ) {
$(this).addClass("trSelected");
}
});
}

Categories