How do you replace/remove rows during a dataTable update? - javascript

So, I am working on code that uses the DataTables API. It appears that it is using an older version of it though. So, my table updates every 5 seconds and all I need is for it to completely update when new new data comes in. However, while it input new update, data that is no longer referenced in that table stay there even though it should disappear, and my table just gets bigger and bigger over time. I've tried to use:
Table.fnClearTable(); // throws error below
TypeError: Cannot set property '_aData' of undefined
And this doesn't work. It removes everything, but won't let me rebuild a new table. I've also tried to use:
Table.fnDestroy(); // doesn't seem to work either
"bDestroy":true // didn't seem to work, but I couldn't tell
So, this is the particular function that I am working on. I'd like to to periodically either delete and recreate the table, or to do a better job at refreshing the data going into it.
my.updating.graph = function(obj, listAll) {
try {
if (obj == null || obj.updates == null || obj.updates.length == 0) {
$("#sectionUpdates").hide();
return;
}
$("#sectionUpdates").show();
var table = null;
if ($.fn.dataTable.isDataTable("updateTable")) { // may remove this statement...
table = $("#updateTable").dataTable();
} else {
table = $("#updateTable").dataTable({ // is there a reset option?
"paging": !listAll,
"pagingType": !listAll ? "X" : "Y",
"searching": true,
"order": [
[0, "desc"]
],
"ordering": true,
"oLanguage": {
"sEmptyTable": "No updates at this time"
},
"iDisplayLength": 15,
"info": false,
"formatNumber": function(format) {
return friendlyFormat(format, 1000, 0);
},
"aoColumns": [{
"bVisible": false
},
{
"className": "dt-center",
"width": "10%",
"iDataSort": 0,
"render": function(data, type, row) {
return extractData(data, type, row[0]);
}
}, {
"sType": "mixed-string",
"className": "dt-left",
"width": "30%",
"render": function(data, type, row) {
return getZData(data, type, row[1]);
}
}, {
"className": "dt-left",
"width": "30%",
"render": function(data, type, row) {
return getYData(data, type, row[2]);
}
}, {
"sType": "mixed-string",
"className": "dt-left",
"width": "30%",
"render": function(data, type, row) {
return getZData(data, type, row[3]);
}
}
]
});
$("#updateTable").resize(function() {});
}
var updates = obj.updates;
for (var i = 0; i < updates.length; i++) {
var update = updates[i];
var id = makeId(update.id);
var triggered = getCurrentUTC();
if (update) {
if (getID("updateTable", id) == null) {
var row = table.fnAddData([
update.field1,
update.field2,
update.field3,
update.field4
]);
var node = $("#updateTable").dataTable().fnSettings().aoData[row[0]].nTr;
node.setAttribute("id", "updateTable-item-" + id);
node.setAttribute("rowIdx", row[0]);
setID("updateTable", id, row[0]);
}
table.fnUpdate([
update.field1,
update.field2,
update.field3,
update.field4
], getID("updateTable", id),
null, false, false);
for (var q = 0; q < tblStatusClasses.length; q++) {
$("updateTable-item-" + id + " td:eq(0)").removeClass(tblStatusClasses[q]);
}
$("#updateTable-item-" + id + " td:eq(0)").addClass("table-state" + update.field1);
}
table.fnStandingRedraw();
}
} catch (e) {
console.log(e);
}
}

Related

How to update ChartJS in a long polling & stop animation stuttering?

I have two issues when i'm trying to update my ChartJS values / datasets, the first is when a new dataset is added to chart datasets it's placed far from other bars (this happens when there are other datasets with zero values in it) in same dataset, another issue is that the data is not updated for same dataset when it's y value is chaged.
Here is what i've tried:
let API = [{
"totpag": 6.5,
"descrpag": "CONTANTI",
"data": "2022-02-15T10:00:00"
},
{
"totpag": 5.5,
"descrpag": "POS MANUALE",
"data": "2022-02-15T10:00:00"
},
{
"totpag": 25,
"descrpag": "ASSEGNI",
"data": "2022-02-15T10:00:00"
}
]
const optionsPagamentiBar = {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
display: false
},
tooltip: {
mode: 'index',
intersect: 0,
usePointStyle: true,
callbacks: {
label: function(context) {
let y = context.parsed.y;
if (y) {
return context.dataset.label + ": " + "€" + context.parsed.y.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,').replace(/[,.]/g, m => (m === ',' ? '.' : ','));
}
}
}
}
},
scales: {
y: {
ticks: {
display: true,
beginAtZero: true,
callback: function(value, index, values) {
return "€" + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
}
},
grid: {
drawBorder: false,
zeroLineColor: "transparent",
}
},
x: {
display: 1,
ticks: {
padding: 10,
display: true,
fontSize: 10
},
grid: {
display: false
}
}
}
}
const chartBarPayments = new Chart(document.getElementById("chartBarPayments").getContext('2d'), {
type: 'bar',
data: {
labels: [],
datasets: [{
data: [],
}]
},
options: optionsPagamentiBar
});
let periodo = 'giorno'
function getColorsByLabels(labels) {
//const colorScale = d3.interpolateSinebow;
//const colorRangeInfo = {
// colorStart: 0.2,
// colorEnd: 1,
// useEndAsStart: true,
//};
//let COLORS = interpolateColors(labels.length, colorScale, colorRangeInfo);
let COLORS = ["rgb(167, 3, 213)", "rgb(255, 64, 64)", "rgb(24, 114, 244)", "rgb(34, 0, 97)"]
let backgroundColors = {};
COLORS.forEach((color, index) => {
backgroundColors[labels[index]] = color;
})
return backgroundColors;
}
function pagamentiPerFascia(pagamenti) {
let datasets = [];
let timePeriods = [];
let datasetLabels = [];
let indexedData = {};
pagamenti.forEach((pagamento, i) => {
let date = "";
if (periodo == "anno") {
date = moment(pagamento.data).format("MMM YYYY");
} else if (periodo == "mese") {
date = moment(pagamento.data).format("DD MMM");
} else {
date = moment(pagamento.data).format('HH:mm');
}
if (!timePeriods.includes(date)) {
timePeriods.push(date);
}
if (!datasetLabels.includes(pagamento.descrpag)) {
datasetLabels.push(pagamento.descrpag);
}
indexedData[pagamento.descrpag + date] = pagamento.totpag;
})
let backgroundColors = getColorsByLabels(datasetLabels);
datasetLabels.forEach(label => {
const dataset = {
label,
backgroundColor: backgroundColors[label],
data: [],
skipNull: true,
};
timePeriods.forEach(date => {
dataset.data.push({
x: date,
y: indexedData[label + date] || null
})
})
datasets.push(dataset);
})
updateChart(datasets)
}
function updateChart(datasets) {
chartBarPayments.data = {};
datasets.forEach((dataset) => {
// checking if dataset exists in chart
let chartdataset = chartBarPayments.data.datasets.find((data) => data.label === dataset.label);
if (chartdataset) {
dataset.data.forEach((date) => {
// checking if x value exists in chart dataset
let chartdata = chartdataset.data.find((data) => data.x === date.x);
if (chartdata) {
console.log("if", date.y)
// if x value exists i''m setting it with the new value (even if it's the same)
chartdata.y = date.y || null;
chartBarPayments.update();
} else {
// else pushing a new xy value to data
console.log("else", date.y)
chartdataset.data.push({
x: date.x,
y: date.y || null
})
chartBarPayments.update();
}
})
} else {
// if the dataset does not exists i'm pushing it as a new one
chartBarPayments.data.datasets.push(dataset);
chartBarPayments.update();
}
});
}
pagamentiPerFascia(API)
var longPolling = setInterval(() => {
API[0].totpag = 15;
API.push({
"totpag": 16.5,
"descrpag": "VISA",
"data": "2022-02-15T10:00:00"
});
API.push({
"totpag": 16.5,
"descrpag": "VISA",
"data": "2022-02-15T11:00:00"
});
pagamentiPerFascia(API)
}, 5000)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.7.0/dist/chart.min.js"></script>
<canvas id="chartBarPayments"></canvas>
How can i update the values and is there a way to hide zero values from the chart?
UPDATE:
Solved the issue with spacing between bars by setting null instead of 0 in empty bars and added skipNull to each dataset.
UPDATE 2:
Solved even the issue with value update by replacing
chartData = date;
with
chartData.y = date.y;
The main issue here is that i have to clear the .data every time which cause animation stuttering even when there is no new data, clearing data is needed as the dataset can change any time with all new Y labels.
I ran into a similar situation and I ended up disabling the animation, which obviously solved the problem, but because it looked a bit less dazzling the customer did not like the solution, in the end I had to utilise a hack.
Not sure if this will work for you, but in my case it did, you do this by using setTimeout to 1 millisecond.
Run the update & then set a timeout for a millisecond & run the update again. If this doesn't work, try setting arbitrary data (instead of emptying the data) & then updating to the correct dataset a millisecond later.
In my instance:
refreshScope( endscope ) {
if(this.current_scope == 'today') {
this.current_scope = `week`; // Opposite (changes data on watcher)
} else {
this.current_scope = `today`; // Opposite again.
}
setTimeout(() => {
this.current_scope = `${endscope}`;
}, 1);
}
There are of course other (better) options you can employ, as outlined by ChartJS' performance page:
https://www.chartjs.org/docs/3.1.1/general/performance.html
And ultimately disabling animation will make it seem accurate - not stutter, albeit less dazzling, and not require hacks.
Disabling animation:
new Chart(ctx, {
type: 'line',
data: data,
options: {
animation: false
}
});

remove selectedRow in handsontable using jQuery

I have an handsontable like the below image. After selecting any one of the rows (for example LastName) it should remove that particular row permanently. How can I achieve this using jQuery?
This is my code which I have written using the afterSelection function but I don't know how to delete that row.
this.tab.handsontable({
data: self.data,
dataSchema: {
columnsexpo: null,
placeholder: null
},
colHeaders: ['Columns Export'],
rowHeaders: true,
fixedColumns: true,
fillHandle: {
autoInsertRow: false,
},
columnSorting: true,
columns: [{
data: 'columnsexpo',
readOnly: true
}, ],
stretchH: 'all',
className: "htCenter",
height: 420,
afterChange: function() {},
beforeRemoveRow: function(row, col) {
var m = this.getDataAtCell(row, 0);
var mandatory = true;
self.MandatoryFields.forEach(function(item) {
if (!_.isEmpty(m)) {
var found = m.toLowerCase().includes(item.toLowerCase());
if (found) {
mandatory = false;
}
}
});
if (!mandatory) {
return false
} else
return true;
},
afterSelection: function(r, c) {
var da = this.getDataAtRow(r);
selectedRow = "";
selectedRow = da[0];
console.log(selectedRow);
},
afterRender: function() {
if (init) {
Events.trigger("DEW:ValidRequest", 1, self.checkValid());
}
init = true;
$('#tablesortable thead th div').filter(function() {
return $(this).text() == "Columns Export";
}).popup({
title: 'Columns Export',
position: 'top center'
});
}
});
EDIT
afterSelection: function(r,c,e){
var dat = this.getDataAtRow(r)
this.alter('remove_row', r, 1);
console.log(r);
},
Now after applying above function it is removing selected Row but if i select last row it is removing all previously selected row
use hot.alter('remove_row', 10, 2); inside after selection method of handsontable.
No need for jquery.
Or if you want to use jquery, store the handsontable instance in some varitable and call the same on row selection.
Update -- added deselectCell before removing the row. after removing the row, previous row is getting selected which is causing the problem.
afterSelection: function(r, c, e) {
this.deselectCell()
this.alter('remove_row', r, 1);
}

jquery $.ajax request remains pending in IE 11 works in chrome and firefox

I am trying to get an excel file downloaded, the problem is that it doesnt work in IE 11. It works fine on chrome and firefox but when ever I run it on IE I get request pending and it doesn't go away:
Here is the code for my ajax call:
$('#partTable').dataTable( {
"processing": true,
"serverSide": true,
"pageLength": 50,
"bSort" : true,
"order": [],
"language": {
"lengthMenu": ""
},
"ajax": {
cache: false,
url: $('#url').val(),
type: "POST",
data: function (d) {
//("in data function");
if( $('#filter0').val() !=''){
d.columns[0]['search']['regex'] = true;
d.columns[0]['search']['value'] = $('#filter0').val();
$('#pageHeaderL2').html("<button class='myButton' style='cursor:default;' type='button' name='" + $('#filter0').val() + "'>" + $('#filter0').val() + "</button>");
//("set default facility");
}
if( $('#filter1').val() !=''){
d.columns[1]['search']['regex'] = true;
d.columns[1]['search']['value'] = $('#filter1').val();
$('#pageHeaderL5').html("<button class='myButton' style='cursor:default;' type='button' name='" + $('#filter0').val() + ":" + $('#filter1').val() + "'>" + $('#filter0').val() + ":" + $('#filter1').val() + "</button>");
//("set default module");
}
if($('#searchValueIn').val() != "")// depending on if you module search or global search the search string is stored in a different location, this saves the search val in a string
var searchVal = $('#searchValueIn').val();
else
var searchVal = $('#searchValueLocal').val();
var dd = $.extend({}, d, {
"originalSearchValue": searchVal
//"useDefaultFacility": $('#filter0').val() !='' ? true : false,
//"useDefaultModule": $('#filter1').val() !='' ? true : false,
});
currentTableMeta = dd;
return dd;
},
dataSrc: function(json) {
for ( var i=0, ien=json.data.length ; i<ien ; i++ ) {
json.data[i][0] = '<a href="/message/'+json.data[i][0]+'>View message</a>';
}
if($('#searchValueIn').val() != "")
var searchVal = $('#searchValueIn').val();
else
var searchVal = $('#searchValueLocal').val();
var hrefExcel= $('#excelurl').val() +'?searchValue='+ searchVal +'&' + $.param(currentTableMeta) ;
// debugger;
if($('#tableExcel').length < 1) {
$('#partTable_filter').css({left: 10, position:'absolute'});
$('#partTable_filter').prepend($('<a id="tableExcel" href="' + hrefExcel + '" class="btn" style="float:right; margin-left: 5px;"><i class="icon-table"></i> Excel</a>'));
/* $('#tableExcel').on("click",function(e) {
//var abc = $(currentTableMeta).serialize();
var abc = $.param(currentTableMeta);
debugger; }); */
// alert("in the IF");
$('#partTable_processing').before("<br /><br />");
}else{
$("#tableExcel").attr('href',hrefExcel);
//alert("in the else");
alert("After the Click");
}
tableSortRowObj = $("#sortRowState");
//("this current sort:" + tableSortRowObj);
updateFilterFields(json);
//("to isnert:" + newRowOfFilters);
return json.data;
}
},
"fnDrawCallback": function( oSettings ) {
//( 'DataTables has redrawn the table' );
if(!tableLoadedOnce){
$('#partTable > tbody').prepend('<tr id="sortRowState">' + newRowOfFilters +'</tr>');
}
else{
//("add this value:" + tableSortRowObj);
$('#partTable > tbody').prepend(tableSortRowObj);
var emptyRows = $('#partTable > tbody > tr > td.dataTables_empty');
// ("this size:" + emptyRows.size());
if(emptyRows.size() > 1){
emptyRows.eq(1).remove();
}
}
$('#col0Filter > select').prop("disabled",false);
$('#col1Filter > select').prop("disabled",false);
$('#col6Filter > select').prop("disabled",false);
tableLoadedOnce=true;
//("about to hightlight");
//collect all the words to highlight across current filters
//$("#partTable").highlight("spider");
//$("#partTable").highlight("valve");
$.each( highlightMap, function( key, val ) {
$.each(val.split(" "),function(index, value){
$("#partTable").highlight(value);
});
});
},
"columns": [
{ "data": "facility", "bVisible": false},
{ "data": "module", "bVisible": false},
{ "data": "partIdView","width": "60px"},
{ "data": "currentLocation", "width" : "160px"},
{ "data": "classification","width": "110px"},
{ "data": "partType", "width": "130px"},
{ "data": "serial", "width": "130px"},
{ "data": "status","width": "110px"},
{ "data": "quantity","width": "40px"},
{ "data": "oemopm", "width": "200px"},
{ "data": "tiIdentification", "width": "120px"},
{ "data": "poNumber", "width": "120px"},
{ "data": "description", "width": "160px"},
{ "data": "altDescription", "width": "160px"},
{ "data": "toolModel","width": "110px"},
<c:if test="${currentModule.freeTradeZone }">
{ "data": "cdfNumber","width": "180px"},
</c:if>
{ "data": "shortText","width": "110px"},
{ "data": "toolModel","width": "140px","bVisible":false},
{ "data": "partCheckout","width": "140px","visible":false}
] });
I also get the following error from my server:
Aug 16, 2016 12:16:20 PM org.apache.coyote.http11.AbstractHttp11Processor process INFO: Error parsing HTTP request header
Any help would be appreciated. Thank You.

Handsonetable - can't hide columns

I'm trying to hide few colums. Here is my code:
function setTable(options){
var data = options.data;
var container = options.container;
var dataSchema = options.dataSchema;
var colHeaders = options.colHeaders;
var columns = options.columns;
var table = new Handsontable(container, {
data: data,
disableVisualSelection:true,
dataSchema: dataSchema,
colHeaders:colHeaders,
columns:columns,
currentRowClassName: 'selected',
columnSorting:true,
columnStreching:true,
autoColumnSize: true,
stretchH: 'all',
outsideClickDeselects: false
});
Handsontable.hooks.add('afterSelectionEnd', function(e){
var data = this.getDataAtRow(e);
moveToAlert({
n:data[1],
v:data[4],
lt:data[7],
ln:data[8]
});
}, table);
Handsontable.hooks.add('afterOnCellMouseOver', function(e,c){
var data = this.getDataAtRow(c.row);
if(data[0] == null) return false;
moveToAlert({
n:data[1],
v:data[4],
lt:data[7],
ln:data[8]
})
}, table);
return table;
}
actualData.push(
{
reg:d.r,
name:d.n,
fd:d.fd,
td:d.td,
v:d.v,
rgps:d.rg,
loc:"PL, Wrocław, Autostradowa Obwodnica Wrocławia",
lt:d.lt,
ln:d.ln,
c:'a_'+d.c
}
);
}
if (TABLE_ACTUAL) TABLE_ACTUAL.destroy();
TABLE_ACTUAL = setTable({
data:actualData,
container:document.getElementById('actual-table'),
dataSchema:{reg: null, name: null, fd: null, td: null, v: null, rgps: null, loc: null, lt:null, ln:null,c:null},
colHeaders:["Pojazd", "Nazwa", "Od", "Do", "Wartość", "Droga", "Lokalizacja"],
columns:[
{
data:"reg",
editor:false,
},
{
data:"name",
editor:false,
},
{
data:"fd",
editor:false,
},
{
data:"td",
editor:false,
},
{
data:"v",
editor:false,
},
{
data:"rgps",
editor:false,
},
{
data:"loc",
editor:false,
}
],
});
So i want to hide 3 last columns ( lt,ln,c) and also disable editor on all colums. Why this way not working? I dont want to use customrender becouse i think its unnecessary.
EDIT
SOLVED (thanks to #ZekeDroid)
I used getSourceDataAtRow() instead of getDataAtRow().
Also used fix for sorted table: http://docs.handsontable.com/0.16.1/demo-sorting-data.html and more specifically this : physicalIndex = instance.sortIndex[logicalIndex][0]; as a index for selected row.
It's likely due to the dataSchema option. You are including the columns to show there, even if null. Try removing the dataSchema option entirely. But please provide a fiddle so we can be more sure about it.

How can I only display 3 columns in my 13-column slick grid?

I have slick grid in 10 columns .but i need to display only 3 columns only.how is it possible pls any one help me urgent.here my slick grid here slick grid code. This code display all columns default but i want to display only 3 columns.
CSS
.slick-row.selected .cell-selection {
background-color: transparent; /* show default selected row background */
}
HTML
<div style="position:relative">
<div style="width:600px;">
<div class="grid-header" style="width:100%">
<label>SlickGrid</label>
<span style="float:right" class="ui-icon ui-icon-search" title="Toggle search panel"
onclick="toggleFilterRow()"></span>
</div>
<div id="myGrid" style="width:100%;height:500px;"></div>
<div id="pager" style="width:100%;height:20px;"></div>
</div>
<div class="options-panel">
<b>Search:</b>
<hr/>
<div style="padding:6px;">
<label style="width:200px;float:left">Show tasks with % at least: </label>
<div style="padding:2px;">
<div style="width:100px;display:inline-block;" id="pcSlider"></div>
</div>
<br/>
<label style="width:200px;float:left">And title including:</label>
<input type=text id="txtSearch" style="width:100px;">
<br/><br/>
<button id="btnSelectRows">Select first 10 rows</button>
<br/>
<h2>Demonstrates:</h2>
<ul>
<li>a filtered Model (DataView) as a data source instead of a simple array</li>
<li>grid reacting to model events (onRowCountChanged, onRowsChanged)</li>
<li><b>FAST</b> DataView recalculation and <b>real-time</b> grid updating in response to data changes.<br/>The grid holds <b>50'000</b> rows, yet you are able to sort, filter, scroll, navigate and edit as if it had 50 rows.</li>
<li>adding new rows, bidirectional sorting</li>
<li>column options: cannotTriggerInsert</li>
<li>events: onCellChange, onAddNewRow, onKeyDown, onSelectedRowsChanged, onSort</li>
<li><font color=red>NOTE:</font> all filters are immediately applied to new/edited rows</li>
<li>Handling row selection against model changes.</li>
<li>Paging.</li>
<li>inline filter panel</li>
</ul>
<h2>View Source:</h2>
<ul>
<li><A href="https://github.com/mleibman/SlickGrid/blob/gh-pages/examples/example4-model.html"
target="_sourcewindow"> View the source for this example on
Github</a></li>
</ul>
</div>
</div>
</div>
<div id="inlineFilterPanel" style="display:none;background:#dddddd;padding:3px;color:black;">
Show tasks with title including <input type="text" id="txtSearch2"> and % at least
<div style="width:100px;display:inline-block;" id="pcSlider2"></div>
</div>
JavaScript
<script src="slick.grid/lib/firebugx.js"></script>
<script> var dataView; var grid; var data = []; var columns = [
{id: "sel", name: "#", field: "num", behavior: "select", cssClass:
"cell-selection", width: 40, cannotTriggerInsert: true, resizable:
false, selectable: false }, {id: "title", name: "Title", field:
"title", width: 120, minWidth: 120, cssClass: "cell-title", editor:
Slick.Editors.Text, validator: requiredFieldValidator, sortable:
true}, {id: "duration", name: "Duration", field: "duration",
editor: Slick.Editors.Text, sortable: true}, {id: "%",
defaultSortAsc: false, name: "% Complete", field: "percentComplete",
width: 80, resizable: false, formatter:
Slick.Formatters.PercentCompleteBar, editor:
Slick.Editors.PercentComplete, sortable: true}, {id: "start", name:
"Start", field: "start", minWidth: 60, editor: Slick.Editors.Date,
sortable: true}, {id: "finish", name: "Finish", field: "finish",
minWidth: 60, editor: Slick.Editors.Date, sortable: true}, {id:
"effort-driven", name: "Effort Driven", width: 80, minWidth: 20,
maxWidth: 80, cssClass: "cell-effort-driven", field: "effortDriven",
formatter: Slick.Formatters.Checkmark, editor:
Slick.Editors.Checkbox, cannotTriggerInsert: true, sortable: true} ];
var options = { editable: true, enableAddRow: true,
enableCellNavigation: true, asyncEditorLoading: true,
forceFitColumns: false, topPanelHeight: 25 };
var sortcol = "title"; var sortdir = 1; var percentCompleteThreshold
= 0; var searchString = "";
function requiredFieldValidator(value) { if (value == null || value
== undefined || !value.length) {
return {valid: false, msg: "This is a required field"}; } else {
return {valid: true, msg: null}; } }
function myFilter(item, args) { if (item["percentComplete"] <
args.percentCompleteThreshold) {
return false; }
if (args.searchString != "" &&
item["title"].indexOf(args.searchString) == -1) {
return false; }
return true; }
function percentCompleteSort(a, b) { return a["percentComplete"] -
b["percentComplete"]; }
function comparer(a, b) { var x = a[sortcol], y = b[sortcol];
return (x == y ? 0 : (x > y ? 1 : -1)); }
function toggleFilterRow() {
grid.setTopPanelVisibility(!grid.getOptions().showTopPanel); }
$(".grid-header .ui-icon")
.addClass("ui-state-default ui-corner-all")
.mouseover(function (e) {
$(e.target).addClass("ui-state-hover")
})
.mouseout(function (e) {
$(e.target).removeClass("ui-state-hover")
});
$(function () { // prepare the data for (var i = 0; i < 50000;
i++) {
var d = (data[i] = {});
d["id"] = "id_" + i;
d["num"] = i;
d["title"] = "Task " + i;
d["duration"] = "5 days";
d["percentComplete"] = Math.round(Math.random() * 100);
d["start"] = "01/01/2009";
d["finish"] = "01/05/2009";
d["effortDriven"] = (i % 5 == 0); }
dataView = new Slick.Data.DataView({ inlineFilters: true }); grid
= new Slick.Grid("#myGrid", dataView, columns, options); grid.setSelectionModel(new Slick.RowSelectionModel());
var pager = new Slick.Controls.Pager(dataView, grid, $("#pager"));
var columnpicker = new Slick.Controls.ColumnPicker(columns, grid,
options); // columnpicker = new Slick.Controls.ColumnPicker(Columns,
Grid, GridOptions); //grid.setSelectedcolumn([]); // move the
filter panel defined in a hidden div into grid top panel
$("#inlineFilterPanel")
.appendTo(grid.getTopPanel())
.show();
grid.onCellChange.subscribe(function (e, args) {
dataView.updateItem(args.item.id, args.item); });
grid.onAddNewRow.subscribe(function (e, args) {
var item = {"num": data.length, "id": "new_" + (Math.round(Math.random() * 10000)), "title": "New task",
"duration":
"1 day", "percentComplete": 0, "start": "01/01/2009", "finish":
"01/01/2009", "effortDriven": false};
$.extend(item, args.item);
dataView.addItem(item); });
grid.onKeyDown.subscribe(function (e) {
// select all rows on ctrl-a
if (e.which != 65 || !e.ctrlKey) {
return false;
}
var rows = [];
for (var i = 0; i < dataView.getLength(); i++) {
rows.push(i);
}
grid.setSelectedRows(rows);
e.preventDefault(); });
grid.onSort.subscribe(function (e, args) {
sortdir = args.sortAsc ? 1 : -1;
sortcol = args.sortCol.field;
if ($.browser.msie && $.browser.version <= 8) {
// using temporary Object.prototype.toString override
// more limited and does lexicographic sort only by default, but can be much faster
var percentCompleteValueFn = function () {
var val = this["percentComplete"];
if (val < 10) {
return "00" + val;
} else if (val < 100) {
return "0" + val;
} else {
return val;
}
};
// use numeric sort of % and lexicographic for everything else
dataView.fastSort((sortcol == "percentComplete") ? percentCompleteValueFn : sortcol, args.sortAsc);
} else {
// using native sort with comparer
// preferred method but can be very slow in IE with huge datasets
dataView.sort(comparer, args.sortAsc);
} });
// wire up model events to drive the grid
dataView.onRowCountChanged.subscribe(function (e, args) {
grid.updateRowCount();
grid.render(); });
dataView.onRowsChanged.subscribe(function (e, args) {
grid.invalidateRows(args.rows);
grid.render(); });
dataView.onPagingInfoChanged.subscribe(function (e, pagingInfo) {
var isLastPage = pagingInfo.pageNum == pagingInfo.totalPages - 1;
var enableAddRow = isLastPage || pagingInfo.pageSize == 0;
var options = grid.getOptions();
if (options.enableAddRow != enableAddRow) {
grid.setOptions({enableAddRow: enableAddRow});
} });
var h_runfilters = null;
// wire up the slider to apply the filter to the model
$("#pcSlider,#pcSlider2").slider({
"range": "min",
"slide": function (event, ui) {
Slick.GlobalEditorLock.cancelCurrentEdit();
if (percentCompleteThreshold != ui.value) {
window.clearTimeout(h_runfilters);
h_runfilters = window.setTimeout(updateFilter, 10);
percentCompleteThreshold = ui.value;
}
} });
// wire up the search textbox to apply the filter to the model
$("#txtSearch,#txtSearch2").keyup(function (e) {
Slick.GlobalEditorLock.cancelCurrentEdit();
// clear on Esc
if (e.which == 27) {
this.value = "";
}
searchString = this.value;
updateFilter(); });
function updateFilter() {
dataView.setFilterArgs({
percentCompleteThreshold: percentCompleteThreshold,
searchString: searchString
});
dataView.refresh(); }
$("#btnSelectRows").click(function () {
if (!Slick.GlobalEditorLock.commitCurrentEdit()) {
return;
}
var rows = [];
for (var i = 0; i < 10 && i < dataView.getLength(); i++) {
rows.push(i);
}
grid.setSelectedRows(rows); });
// initialize the model after all the events have been hooked up
dataView.beginUpdate(); dataView.setItems(data);
dataView.setFilterArgs({
percentCompleteThreshold: percentCompleteThreshold,
searchString: searchString }); dataView.setFilter(myFilter); dataView.endUpdate();
// if you don't want the items that are not visible (due to being
filtered out // or being on a different page) to stay selected,
pass 'false' to the second arg dataView.syncGridSelection(grid,
true);
$("#gridContainer").resizable(); }) </script>
I think the easiest way is to only add the 3 columns you want to be visible to the "columns" variable.
If you want to show more columns at a later time you can add more columns on the fly (refer to this stackoverflow question on how to do this: Can I add a column to slickgrid on on the fly? )
Update: Example to only show the first 3 columns
insert this line:
columns = columns.slice(0, 3);
before the following line:
grid = new Slick.Grid("#myGrid", dataView, columns, options);

Categories

Resources