Make variable accessible through whole function - javascript

I have the following function:
var handsonTableHandler = (function () {
var container = document.getElementById('WebGrid');
var hot = "";
var init = function () {
//container is null here, why?
Handsontable.renderers.registerRenderer('dataStyling', dataStyling);
hot = new Handsontable(container, {
startRows: 18,
startCols: 24,
autoWrapRow: true,
width: 1400,
height: 441,
rowHeaders: true,
colHeaders: true,
outsideClickDeselects: false,
search: true,
manualColumnResize: true,
stretchH: "all",
afterChange: function (source, changes) {},
cells: function (row, col, prop) {
var cellProperties = {};
cellProperties.renderer = "dataStyling"; // uses lookup map
cellProperties;
}
});
}
}
$(document).ready(function() {
handsonTableHandler.init();
});
I want the container and hot variable to be accessible through the whole function, thus, in the init function and other functions that are defined here.
As you can see, I'm getting the element for with the Id WebGrid. But in the init-function, it's null. Why is this?

If it was not accessable in the inner function, it would be "Undefined" instead of "Null", therefore it is accessable
you did
var container = document.getElementById('WebGrid');
but document.getElementById(...) returns Null if the element does not exist, therefore there mustnt have been an element with the id of WebGrid
Try in the console and type
document.getElementById('WebGrid')
if it returns null, then there was no element in the first place
now change your code to:
$(document).ready(function() {
var handsonTableHandler = (function () {
var container = document.getElementById('WebGrid');
var hot = "";
var init = function () {
//container is null here, why?
Handsontable.renderers.registerRenderer('dataStyling', dataStyling);
hot = new Handsontable(container, {
startRows: 18,
startCols: 24,
autoWrapRow: true,
width: 1400,
height: 441,
rowHeaders: true,
colHeaders: true,
outsideClickDeselects: false,
search: true,
manualColumnResize: true,
stretchH: "all",
afterChange: function (source, changes) {},
cells: function (row, col, prop) {
var cellProperties = {};
cellProperties.renderer = "dataStyling"; // uses lookup map
cellProperties;
}
});
};
})();
handsonTableHandler.init();
});

The only to fix this, is to assign the DOM element to container in init, like this:
var handsonTableHandler = (function () {
var container,
hot;
var init = function () {
container = document.getElementById('WebGrid');
//container is null here, why?
Handsontable.renderers.registerRenderer('dataStyling', dataStyling);
hot = new Handsontable(container, {
startRows: 18,
startCols: 24,
autoWrapRow: true,
width: 1400,
height: 441,
rowHeaders: true,
colHeaders: true,
outsideClickDeselects: false,
search: true,
manualColumnResize: true,
stretchH: "all",
afterChange: function (source, changes) {},
cells: function (row, col, prop) {
var cellProperties = {};
cellProperties.renderer = "dataStyling"; // uses lookup map
cellProperties;
}
});
}
})()

You can change you function to create handler with new syntax and get access to .init function
let handsonTableHandler = function () {
this.container = document.getElementById('WebGrid');
this.hot = "";
this.init = function () {
console.log('container', this.container);
Handsontable.renderers.registerRenderer('dataStyling', dataStyling);
this.hot = new Handsontable(this.container, {
startRows: 18,
startCols: 24,
autoWrapRow: true,
width: 1400,
height: 441,
rowHeaders: true,
colHeaders: true,
outsideClickDeselects: false,
search: true,
manualColumnResize: true,
stretchH: "all",
afterChange: function (source, changes) {},
cells: function (row, col, prop) {
var cellProperties = {};
cellProperties.renderer = "dataStyling"; // uses lookup map
cellProperties;
}
});
}
}
let handler = new handsonTableHandler();
$(document).ready(function() {
handler.init(); // output: container not null
});

to me it seems you are not running the function so the closure is never created, I added a few parenthesis, this should create the closure:
var handsonTableHandler = function () {
var container = document.getElementById('WebGrid');
var hot = "";
var init = function () {
//container is null here, why?
Handsontable.renderers.registerRenderer('dataStyling', dataStyling);
hot = new Handsontable(container, {
startRows: 18,
startCols: 24,
autoWrapRow: true,
width: 1400,
height: 441,
rowHeaders: true,
colHeaders: true,
outsideClickDeselects: false,
search: true,
manualColumnResize: true,
stretchH: "all",
afterChange: function (source, changes) {},
cells: function (row, col, prop) {
var cellProperties = {};
cellProperties.renderer = "dataStyling"; // uses lookup map
cellProperties;
}
});
}
return {init: init}
};
$(document).ready(function() {
handsonTableHandler().init();
});

Related

How do I change floatingFilter option after Init of AGGrid?

I'm using AgGrid with JavaScript module. I'm trying to change the value of floatingFilter after init of Grid by calling api.refreshHeader method but it's not working.
function getServices() {
var columnDefs = [
{ field: 'name', headerName: 'Name' },
{ field: 'Category', headerName: 'Category' },
];
var gridOptions = {
animateRows: true,
columnDefs: columnDefs,
defaultColDef: {
resizable: true,
filter: true,
sortable: true,
flex: 1,
},
floatingFilter: true, // I want to change this after init
};
var gridDiv = document.querySelector('#serviceGrid');
var gridInstance = new agGrid.Grid(gridDiv, gridOptions);
$.ajax({
type: 'GET',
dataType:"JSON",
url: 'FROM_URL',
success:function(data){
gridOptions.api.setRowData(data)
}
});
// For testing purpose I'm using timeout
setTimeout(function() {
gridInstance.gridOptions.floatingFilter = false;
gridInstance.gridOptions.api.refreshHeader();
}, 5000)
}
Correct me if I'm wrong anywhere.
I am not sure which version you are using, but in the latest version, floatingFilters go inside columnDefinitions and not inside gridOptions.
Move floatingFilters inside defaultColDef in your gridOptions.
var gridOptions = {
animateRows: true,
columnDefs: columnDefs,
defaultColDef: {
resizable: true,
filter: true,
sortable: true,
flex: 1,
floatingFilter: true, // I want to change this after init
},
};
and then change your setTimeout function to this.
// For testing purpose I'm using timeout
setTimeout(function() {
gridInstance.gridOptions.defaultColDef.floatingFilter = false;
gridInstance.gridOptions.api.refreshHeader();
}, 5000)
Here is a plnkr I forked from one of their examples that works.
Hope I was able to help.

jqgrid load save state data doesn't load dynamicly

I have jqgrid page with a lot of columns. Idea is to allow user choose columns and their order in table and save this order and column count in cookies. For this purposes I use $.jgrid.saveState() for saving and $.jgrid.loadState() for restoring jqgrid options from cookies. This methods works fine. But I don't want to save data to storage: only column order and filter. I tried option restoreData: false and storeData: false, but it didn't work.
Here the code of my jqgrid:
jQuery(function ($) {
var table = $("#table");
var pager = "#pager";
var search_panel = "#search";
var localization = globalLocale;
var colNames = [ "Mobile direction total time (sec)", "Mobile direction q-ty ", "Mobile time Percent",
"City direction total time (sec)", "City direction q-ty", 'City time Percent' ];
var exportToCsvBut = "Export to excell";
resizeToFitPageSize(table);
resizeOnSidebar(table);
$(function () {
var d = new Date();
var month = d.getMonth();
var day = d.getDate();
var year = d.getFullYear();
var defCurDate = moment().startOf('day').format('DD.MM.YYYY HH:mm:ss');
var defNextDate = moment().endOf('day').format('DD.MM.YYYY HH:mm:ss');
var from = $('#datetimepickerFrom');
var to = $('#datetimepickerTo');
if (from.val() === "" || to.val() === "") {
from.val(defCurDate);
to.val(defNextDate);
}
$("#datetimepickerFrom").datetimepicker({
dateFormat: 'dd.mm.yy',
timeFormat: 'HH:mm:ss',
defaultDate: new Date(year, month, day + 1, 00, 00),
onClose: function () {
beforeRefresh();
}
});
$("#datetimepickerTo").datetimepicker({
dateFormat: 'dd.mm.yy',
timeFormat: 'HH:mm:ss',
defaultDate: new Date(year, month, day + 1, 00, 00),
onClose: function () {
beforeRefresh();
}
});
defCurDate = $('#datetimepickerFrom').val();
defNextDate = $('#datetimepickerTo').val();
});
var initDate = function (elem) {
$(elem).datetimepicker({
dateFormat: 'd.m.Y H:i:s',
showButtonPanel: true
});
};
var template = {width: 160, fixed: true, align: 'center', editable: false, stype: 'text'};
var colModel = [
{
name: 'mobileDirectionTotalTime',
index: 'mobileDirectionTotalTime',
sortname: 'mobileDirectionTotalTime',
template: template,
formatter: nullFormatter,
sorttype: 'number'
},
{
name: 'mobileDirectionQty',
index: 'mobileDirectionQty',
sortname: 'mobileDirectionQty',
template: template,
formatter: nullFormatter,
sorttype: 'number'
},
{
name: 'mobileDirectionPercent',
index: 'mobileDirectionPercent',
sortname: 'mobileDirectionPercent',
width: 120,
fixed: true, align: 'center', editable: false,
template: "number",
sorttype: 'number'
},
{
name: 'cityDirectionTotalTime',
edittype: "custom",
sortname: 'cityDirectionTotalTime',
formatter: null,
sorttype: 'number'
},
{
name: 'cityDirectionQty',
index: 'cityDirectionQty',
sortname: 'cityDirectionQty',
template: template,
sorttype: 'number'
},
{
name: 'cityDirectionTimePercent',
index: 'cityDirectionTimePercent',
sortname: 'cityDirectionTimePercent',
template: template,
sorttype: 'number'
},
];
table.jqGrid({
url: URL_DATA,
datatype: "json",
jsonReader: {
repeatitems: true
},
height: 'auto',
colNames: colNames,
colModel: colModel,
shrinkToFit: false,
forceFit: true,
pager: pager,
toppager: true,
rowNum: 10,
rowList: [5, 10, 15, 20, 25, 30],
loadonce: true,
viewrecords: true,
storeNavOptions : true,
// navOptions: {reloadGridOptions: {fromServer: true}},
loadComplete: function () {
var table = this;
setTimeout(function () {
updatePagerIcons(table);
enableTooltips(table);
}, 0);
},
gridComplete: function () {
/*var idarray = table.jqGrid('getDataIDs');
if (idarray.length > 0) {
var firstid = table.jqGrid('getDataIDs')[0];
table.setSelection(firstid);
}*/
}
});
$(window).triggerHandler('resize.jqGrid');//trigger window resize to make the grid get the correct size
function beforeRefresh() {
var from = $('#datetimepickerFrom');
var to = $('#datetimepickerTo');
if (from.val() != null && from.val() != '' && to.val() != null && to.val() != '') {
resetFilter('table', 'globalSearchText');
table.jqGrid().setGridParam({datatype: 'json'}).setGridParam({url: URL_DATA + "?from=" + from.val() + "&to=" + to.val()}).trigger("reloadGrid")
if (from.val() === "" || to.val() === "") {
from.val(defCurDate);
to.val(defNextDate);
}
}
}
//navButtons
table.jqGrid('navGrid', pager,
{ //navbar options
cloneToTop: true,
edit: false,
add: false,
del: false,
search: true,
searchicon: 'ace-icon fa fa-search orange',
refresh: true,
beforeRefresh: function () {
var from = $('#datetimepickerFrom');
var to = $('#datetimepickerTo');
if (from.val() != null && from.val() != '' && to.val() != null && to.val() != '') {
resetFilter('table', 'globalSearchText');
table.jqGrid().setGridParam({datatype: 'json'}).setGridParam({url: URL_DATA + "?from=" + from.val() + "&to=" + to.val()}).trigger("reloadGrid")
if (from.val() === "" || to.val() === "") {
from.val(defCurDate);
to.val(defNextDate);
}
}
},
refreshicon: 'ace-icon fa fa fa-refresh green',
view: true,
viewicon: 'ace-icon fa fa-search-plus grey'
}, {}, {}, {},
{
multipleSearch: true,
searchOnEnter: true,
closeOnEscape: true,
multipleSearch: true,
closeAfterSearch: true
},
{
//view record form
recreateForm: true,
beforeShowForm: function (e) {
var form = $(e[0]);
form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />')
form.closest('div.ui-jqdialog').center();
}
}
);
addToolButton({
caption: "",
buttonicon: "ace-icon fa fa-calculator blue",
title: "Выбрать столбцы",
onClickButton: function () {
$(this).jqGrid('columnChooser',
{
width: 550,
msel_opts: {dividerLocation: 0.5}, modal: true
});
$("#colchooser_" + $.jgrid.jqID(this.id) + ' div.available>div.actions')
.prepend('<label style="float:left;position:relative;margin-left:0.6em;top:0.6em">Поиск:</label>');
}
}, table, pager);
addSearchField('table', 'globalSearchText');
$(window).triggerHandler('resize.jqGrid');
table.triggerHandler("jqGridAfterGridComplete");
destroyGrid(table);
$('#table')
.append($("<div style='margin-top: 10px'>" +
"<button id='savestate'>save state</button>" +"<button id='loadstate'>load state</button>" +
"</div>"));
$("#savestate").click(function(){
$.jgrid.saveState("table");
});
$("#loadstate").click(function(){
$.jgrid.loadState("table", {}, {});
})
});
document.addEventListener('contextmenu', function (e) {
e.preventDefault();
});
Here the view of table page:
After user press load state and save state it displays data which was before but not actual:
It just show data which was saved in localstorage.
If I add storeData: false it just diplayed table with no data and doens't load new data from server.
Can anyone help?
P.S In case someone will have the same problem:
$("#table").jqGrid().setGridParam({datatype:'json'}).setGridParam({url : URL_DATA}).trigger("reloadGrid"); after $.jgrid.loadState("table", '', { restoreData: false}); will load new data in loaded grid.
I recommend you to use restoreData: false in loadState and after this command to reload the grid with trigger by example
$("#loadstate").click(function(){
$.jgrid.loadState("table", '', { restoreData: false});
$("#table").trigger("reloadGrid");
});
This will reload fresh grid data from server with the current setting

instance.rootElement.getAttribute is not a function

I am trying to use handsontable in application and doing some experiment with the code. I am now facing the error-"instance.rootElement.getAttribute is not a function". When I check it occurs at line of code
hot = new Handsontable(container, {
My index.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script type="text/javascript" src="https://docs.handsontable.com/0.16.1/scripts/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.js"></script>
<script type="text/javascript"src="https://docs.handsontable.com/0.16.1/bower_components/handsontable/dist/handsontable.full.js"></script>
<script type="text/javascript" src="js/dragresize.js"></script>
<link type="text/css" rel="stylesheet" href="https://docs.handsontable.com/0.16.1/bower_components/handsontable/dist/handsontable.full.min.css">
</head>
<body >
<div id="example1" class="hot handsontable htRowHeaders htColumnHeaders" data-drag-resize></div>
</body>
</html>
My dragresize.js
angular.module('myApp',[]).directive('dragResize',function(){
return{
restrict: 'AEC',
replace:true,
controller: function($scope, $timeout){
//document.addEventListener("DOMContentLoaded", function() {
var container = angular.element(document.getElementById('example1')),
hot;
hot = new Handsontable(container, {
data: Handsontable.helper.createSpreadsheetData(200, 10),
rowHeaders: true,
colHeaders: true,
colWidths: [55, 80, 80, 80, 80, 80, 80],
rowHeights: [50, 40, 100],
manualColumnResize: true,
manualRowResize: true
});
function bindDumpButton() {
if (typeof Handsontable === "undefined") {
return;
}
Handsontable.Dom.addEvent(document.body, 'click', function (e) {
var element = e.target || e.srcElement;
if (element.nodeName == "BUTTON" && element.name == 'dump') {
var name = element.getAttribute('data-dump');
var instance = element.getAttribute('data-instance');
var hot = window[instance];
console.log('data of ' + name, hot.getData());
}
});
}
bindDumpButton();
$timeout(dragResize,0);
//});
}
};
});
/* document.addEventListener("DOMContentLoaded", function() {
var
container = document.getElementById('example1'),
hot;
hot = new Handsontable(container, {
data: Handsontable.helper.createSpreadsheetData(200, 10),
rowHeaders: true,
colHeaders: true,
colWidths: [55, 80, 80, 80, 80, 80, 80],
rowHeights: [50, 40, 100],
manualColumnResize: true,
manualRowResize: true
});
function bindDumpButton() {
if (typeof Handsontable === "undefined") {
return;
}
Handsontable.Dom.addEvent(document.body, 'click', function (e) {
var element = e.target || e.srcElement;
if (element.nodeName == "BUTTON" && element.name == 'dump') {
var name = element.getAttribute('data-dump');
var instance = element.getAttribute('data-instance');
var hot = window[instance];
console.log('data of ' + name, hot.getData());
}
});
}
bindDumpButton();
$timeout(container,0);
}); */
I am not sure what does this error exactly means. I am trying to integrate the existing javascript file in my angularjs file. Any information/help would be much appreciated
thanks.
Replace
container = angular.element(document.getElementById('example1'))
to
container = $document[0].getElementById('example1')
And add $document to your function param just like
directive('dragResize', function($document) { ... }
Hope this helps.
Ask me for more queries.
Thanks.

Freeze columns after move

I would like to freeze two columns after I move them.
ex: JSFiddle
var
myData = Handsontable.helper.createSpreadsheetData(10, 50),
container = document.getElementById('example1'),
hot;
hot = new Handsontable(container, {
data: myData,
rowHeaders: false,
colHeaders: true,
preventOverflow: 'horizontal',
allowInsertRow: false,
allowInsertColumn: false,
fixedColumnsLeft: 2,
contextMenu: false,
manualColumnMove: [2, 5],
manualColumnFreeze: true
});
But it's possible to move them again after manually...
How can I block the manual move after I move them in option ?
Or just freeze the fixed column ?
Thanks guys ;)
I finally find how to freeze column, but the guide is always displaying.
Solution : JSFiddle
var
myData = Handsontable.helper.createSpreadsheetData(10, 50),
container = document.getElementById('example1'),
hot,
fixedColumnsLeft = 2;
hot = new Handsontable(container, {
data: myData,
rowHeaders: false,
colHeaders: true,
preventOverflow: 'horizontal',
allowInsertRow: false,
allowInsertColumn: false,
fixedColumnsLeft: fixedColumnsLeft,
contextMenu: false,
manualColumnMove: true,
manualColumnFreeze: true,
beforeColumnMove: setBeforeColumnMove(),
});
function setBeforeColumnMove() {
return function(startColumn, endColumn) {
var manualColumnMove = hot.getPlugin("ManualColumnMove");
if (startColumn < fixedColumnsLeft || endColumn < fixedColumnsLeft) {
manualColumnMove.changeColumnPositions(endColumn, startColumn);
}
}
};

On selection of row in ext js grid checkbox gets selected

I am using Ext.grid.CheckboxSelectionModel with Ext.grid.GridPanel to display grid with checkbox column.
But when I am clicking on row checkbox also get seleted.
I want checkbox should not get selected while selecting row of grid.
Is there any way to achieve this.
Below is my code snippet.
var cboxSelModel =new Ext.grid.CheckboxSelectionModel({
checkOnly : true,
width:100,
header: defaultVal,
id: 'test',
locked: true,
singleSelect: true,
listeners: {
rowselect: function (sm, rIndex, keepExisting, record) {
uncheckIndex = -1;
cIndex =rIndex;
updateDefaultValue();
},
rowdeselect: function (sm, rIndex, keepExisting, record) {
cIndex = -1;
uncheckIndex =rIndex;
updateDefaultValue();
}
}
});
grid = new Ext.grid.GridPanel({
id:'grid',
width:'99%',
border:true,
store: store,
tbar: toolBar,
autoscroll: false,
height :'100px',
autoHeight :false,
sm: cboxSelModel,
cm :cm,
height:150,
layout: 'fit',
stateful: true,
stateId: 'grid',
autoScroll:true,
enableColumnResize : false,
enableColumnMove : false,
viewConfig:{
forceFit:true,
scrollOffset:0
},
autoFitColumns: true,
listeners: {
afterrender: function() {
setSelectedRows();
var store=grid.getStore();
if(store.data.length > 0 ){
Ext.getCmp('btnSort').setDisabled(false);
Ext.getCmp('btnSort').setIconClass('bmcSort');
}
},delay: 1000,
cellClick :function(iView, iCellEl, iColIdx, iRecord, iRowEl, iRowIdx, iEvent){
storeindex = iCellEl;
var record = grid.store.getAt(iCellEl);
var dValue=record.get('displayValue');
var sValue=record.get('storedValue');
var dataArray = getListData();
sValue=dataArray[iCellEl][1];
sValue = Ext.util.Format.htmlDecode(sValue);
dValue = Ext.util.Format.htmlDecode(dValue);
document.getElementById(InputPageComp.ComponentVars.storedValue).value=sValue;
document.getElementById(InputPageComp.ComponentVars.displayValue).value=dValue;
document.getElementById('addbtn_id').style['display']= 'none';
document.getElementById('updatebtn_id').style['display']= 'block';
Ext.getCmp('btnRemove').setDisabled(false);
Ext.getCmp('btnRemove').setIconClass('bmcDeleteSLT');
grid.getSelectionModel().selectRow(iCellEl);
}
}
});
var sm = Ext.create('Ext.selection.CheckboxModel',{
checkOnly: true
});
I have tested. It should work
Try like this (in grid configs):
selModel: {
selType: 'checkboxmodel',
checkOnly: true
}
Fiddle: https://fiddle.sencha.com/#view/editor&fiddle/1ncs

Categories