Why don't the jquery datatable never reinitialize? - javascript

I have trying to get it right but failed. The problem is that when I call filltblServicesReport function which initializes database mainly, it works for the first time but when I call it again then it doesn't load the new data. Eventhough I am destroying it but still it doesn't.
I am loading it via click event of a button.
function filltblServicesReport() {
$('tfoot td#tdTotal').text("");
var url = '#Url.Action("DetailedServiceReport")';
var data = { FromDate: $("#FromDate").val(), ToDate: $("#ToDate").val() }
$.post(url, data, function (response) {
if (response.ReturnStatusJSON == true) {
$("#tbodytblServicesReport").html("");
var i = 1;
$.each(response.lstDetailedServicesReturned, function (i, val) {
$("#tblServicesReport").append($('<tr>').append($('<td>').html(i))
.append($('<td>').html((val.EntryDateTime === null || val.EntryDateTime === "") ? "N/A" : formatJSONDate(val.EntryDateTime)))
.append($('<td>').html(val.InvoiceNo))
.append($('<td>').html(val.CustomerName))
.append($('<td>').html(val.VehicleRegNo))
.append($('<td>').html(val.ServiceName))
.append($('<td>').html(val.ServicePrice))
.append($('<td>').html(val.Commission))
)
i++;
$('tfoot td#tdTotal').text(val.TotalCost);
$('tfoot td#tdTotalCommission').text(val.TotalCommission);
})
$('#tblServicesReport').show();
// $('#tblServicesReport').dataTable().fnDestroy();
$('#tblServicesReport').DataTable({
destroy: true,
bPaginate: false,
dom: 'Bfrtip',
buttons: [
'copyHtml5',
'excelHtml5',
'csvHtml5',
{
extend: 'pdfHtml5',
footer: true,
title: 'Services Report (' + $('#FromDate').val() + ' - ' + $('#ToDate').val() + ')',
customize: function (doc) {
doc.styles.title = {
color: 'gray',
fontSize: '15',
alignment: 'center'
}
doc.content[1].table.widths =
Array(doc.content[1].table.body[0].length + 1).join('*').split('');
doc.styles.tableHeader.fontSize = 10;
doc.styles.tableHeader.alignment = 'left';
doc.styles.tableHeader.color = 'white'
}
},
{
extend: 'print',
footer: true
//title: 'Sales Report'
}
]
});
}
else {
swal("Sorry !", "No Record Found", "error");
$("#tbodytblServicesReport").html("");
}
});
}

$('#tblServicesReport').DataTable.ajax.url.load
Solved it. You can use .ajax.url.load with data table to reinitialize it.

Related

How to add a new row with custom cell Template on button click in to an existing grid

var nameTemplate = ""
function templateFunction() {
if ($scope.useBindScript === true) {
nameTemplate = '<div class="ui-grid-cell-contents"><input type = "file"></div>';
} else {
nameTemplate = '<div class="ui-grid-cell-contents"><input type = "text"></div>';
}
return nameTemplate;
}
$scope.gridOptionsArg = {
enableRowSelection: true,
enableRowHeaderSelection: false,
enableCellEditOnFocus: true,
data: $scope.arginputFiles,
columnDefs: [{
name: 'mark',
cellTemplate: templateFunction()
},
{
name: 'argument',
field: 'index',
enableCellEdit: false
},
{
name: 'value',
field: 'value'
}
]
};
$scope.addRow = function() {
if (condition) {
$scope.gridOptionsArg.data.push({
"argument": "Application",
"value": ""
});
$scope.columns[$scope.columns.length - 2].cellTemplate = templateFunction();
}
}
This is the definition of my grid. Once I click on some button add row function would be called where I want to add a row to the grid with new cellTemplate. Everytime it is returning a textbox.
I have created a plunker with your needs: http://plnkr.co/edit/GKmcwZurGSf6VXjC2gu0?p=preview
The following function creates a new row and add it to the ui-grid data:
vm.addRow = function() {
vm.gridOptions1.data.unshift({"name":"Test", "gender":"Male", "company":"test"});
vm.grid1Api.core.notifyDataChange( uiGridConstants.dataChange.EDIT );
};
I have used the same function to return the template:
function templateFunction() {
var nameTemplate;
if (useBindScript === true) {
nameTemplate = '<div class="ui-grid-cell-contents"><input type = "file"></div>';
} else {
nameTemplate = '<div class="ui-grid-cell-contents"><input type = "text"></div>';
}
return nameTemplate;
}

Error TS2339: Property 'Default' does not exist on type 'string'.**

I am new to Angular 2
- My functionality is working fine in fiddle but when I put in the code base I am getting below errors.
app/components/playing-cables/-update.ts(82,12): error TS2339: Property 'options' does not exist on type 'jQuery'.
app/components/playing-cables/-update.ts(99,21): error TS2339: Property 'Default' does not exist on type 'string'.
storedPreferences.Default = {
dropdown.options = function(data, selectedKey) {
Can you tell me how to fix it.
Providing my code below.
Working code http://jsfiddle.net/yk0up9ht/
import {Component, ElementRef, Inject, OnInit,ViewChild} from '#angular/core';
import { sportService } from '../../services/sport.service';
import {playesRightBarMultiTabComponent} from '../playing-sports/playes-right-bar-multi-tab'
import {playerComponent} from '../player/player.component';
import {ProgressCircle} from '../shared/progress/progress-circle';
import {playeService} from '../../services/playeService';
import {playingsportsEvergreen} from '../playing-sports/playe-sports-evergreen';
import {TextDecoder} from 'text-encoding-shim';
import { Router} from '#angular/router';
import {NetworkCarousel} from '../shared/content/network-carousel';
import {KendoGridComponent} from '../grid/grid.component';
import { TranslateService } from '../../translate/translate.service';
//import { ProgressCircle } from '../shared/progress/progress-circle';
#Component({
selector: 'downlinkBulkUpdate',
templateUrl: "./app/components/playing-cables/downlink-bulk-update.html",
})
export class downlinkBulkUpdate {
public dataSourceVal;
public selectedRowsUID = [];
private count: boolean = true;
private selectAll: boolean;
#ViewChild(KendoGridComponent) private gridkendo: KendoGridComponent;
constructor(public elementRef: ElementRef,private router: Router){
}
private kendocommand = {
edit: { createAt: "bottom" },
group: false,
reorder: true,
resize: true,
sort: true,
filter: { mode: "row,menu" },
autoBind: false,
pager: { messages: { display: "Showing {0} to {1} of {2} entries" } },
model: {},
columns: [],
pagesize: 50,
getComponentUrl: "admin/v1/lockedItems",
saveStatus: false,
excelfileUidName: "ViewUnlockExport",
excelFileName: {
fileName: "ViewUnlockExport",
allPages: true
},
change: function (e) {
console.log("kendocommand downlink-bulk-update");
$('tr').find('[type=checkbox]').prop('checked', false);
$('tr.k-state-selected').find('[type=checkbox]').prop('checked', true);
},
searchFields: []
};
ngOnInit() {
$("tr th[data-field='codeLong']").hide();
if ($('input.checkbox_check').prop('checked')) {
//blah blah
alert("checked");
$("tr th[data-field='codeLong']").show();
}
$("#win1").hide();
/*document.getElementById('cars').options[0].text = localStorage.getItem("someVarName") || 'unkonwn';
var dropdown = $('<select>');
alert("I am here dropdownmenu select"); */
var dropdown = $('#cars');
dropdown.options = function(data, selectedKey) {
var self = this;
var newOptions = '<option value="Default">Default</option>'; //create one objec to save new options
$.each(data, function(ix, val) {
var selected = (val == selectedKey) ? 'selected="selected"' : '';
if (val != 'Default') {
newOptions += '<option value="' + val + '" ' + selected + '>' + val + '</option>';
}
//data.push(option);
});
self.html(newOptions);
self.change();
}
//var array = ['one', 'two', 'three'];
var array = [];
var storedPreferences = localStorage.getItem('preferences');
storedPreferences = (storedPreferences) ? JSON.parse(storedPreferences) : {};
storedPreferences.Default = {
columns: [0,1,2],
};
for (var storedPreference in storedPreferences) {
array.push(storedPreference);
}
dropdown.options(array, 'Default');
//$('body').append(dropdown);
$('#btnSubmit').on('click', function(ix, val) {
//should clear out the current options
//and replace with the new array
alert("I am here dropdownmenu");
var newArray = ['four', 'five', 'six'];
dropdown.options(newArray, 'Default');
});
$("#open1").click(function() {
alert("I am here");
$("#win1").show().kendoWindow({
width: "300px",
height: "500px",
modal: true,
title: "Window 1"
});
$("#win1").data("kendoWindow").open();
});
$("#clearPrefrence").click(function() {
alert("clearPrefrence");
//localStorage.clear();
//$("#cars option[value=volvo]").remove();
if ($('#cars').val() != 'Default') {
var preferences = localStorage.getItem('preferences');
if (preferences) {
preferences = JSON.parse(preferences);
}
else {
preferences = {};
}
delete preferences[$('#cars').val()];
localStorage.setItem('preferences', JSON.stringify(preferences));
$("#cars option:selected").remove();
$("#cars").change();
}
});
$("#win1Submit").click(function() {
var testingMickey = $("#mickey").val();
alert("win1Submit I am here--->" + testingMickey);
//document.getElementById('cars').options[0].text = testingMickey;
var someVarName = testingMickey;
var preferences = localStorage.getItem('preferences');
if (preferences) {
preferences = JSON.parse(preferences);
}
else {
preferences = {};
}
var preference = {
columns: [],
}
$('#rmenu input[type=checkbox]:checked').each(function() {
preference.columns.push($(this).data('index'));
});
preferences[testingMickey] = preference;
localStorage.setItem('preferences', JSON.stringify(preferences));
var getItemsomeVarName1 = localStorage.getItem('preferences');
getItemsomeVarName1 = JSON.parse(getItemsomeVarName1);
var optionArray = [];
for (var key in getItemsomeVarName1) {
optionArray.push(key);
}
alert("getItemsomeVarName1 I am here--->" + getItemsomeVarName1[testingMickey].columns.length);
dropdown.options(optionArray, testingMickey);
$("#win1").data("kendoWindow").close();
});
setGrid();
function toggleColumns() {
$('#rmenu input[type=checkbox]').each(function(index) {
$(this).data('index', index);
$(this).attr('data-index', index);
});
$('#rmenu input[type=checkbox]').change(function() {
var index = $(this).data('index') + 1;
if ($(this).is(':checked')) {
$('.k-grid-header-wrap > table tr th:nth-child(' + index + '),table.k-focusable tr td:nth-child(' + index + ')').show();
}
else {
$('.k-grid-header-wrap > table tr th:nth-child(' + index + '),table.k-focusable tr td:nth-child(' + index + ')').hide();
}
});
$('select').change(function() {
$('#rmenu input[type=checkbox]').removeAttr('checked').prop('checked', false);
var preferences = localStorage.getItem('preferences');
preferences = (preferences) ? JSON.parse(preferences) : {};
var columns = [0,1,2];
var key = $(this).val();
if (preferences && preferences[key]) {
columns = preferences[key].columns;
}
for (var a = 0; a < columns.length; a++) {
$('#rmenu input[type=checkbox][data-index=' + a + ']').prop('checked', true).attr('checked', 'checked');
}
$('#rmenu input[type=checkbox]').each(function() {
$(this).change();
});
});
}
toggleColumns();
$('.k-grid-header').on('contextmenu', function(e) {
e.preventDefault();
let menu = document.getElementById("rmenu");
menu.style.top = e.clientY + 'px';
menu.style.left = e.clientX + 'px';
menu.className = "show";
});
$(document).bind("click", function(event) {
document.getElementById("rmenu").className = "hide";
});
function setGrid() {
var ds1 = new kendo.data.DataSource({
transport: {
read: {
//using jsfiddle echo service to simulate JSON endpoint
url: "/echo/json/",
dataType: "json",
type: "POST",
data: {
// /echo/json/ echoes the JSON which you pass as an argument
json: JSON.stringify({
"country": [{
"codeLong": "AUT",
"codeShort": "AT",
"name": "Austria"
},
{
"codeLong": "BEL",
"codeShort": "BE",
"name": "Belgium"
},
{
"codeLong": "BGR",
"codeShort": "BG",
"name": "Bulgaria"
}
]
})
}
}
},
schema: {
data: "country",
model: {
fields: {
codeLong: {
type: "string"
},
codeShort: {
type: "string"
},
name: {
type: "string"
}
}
}
}
});
$("#grid1").kendoGrid({
dataSource: ds1,
height: 180,
scrollable: {
virtual: true
},
columns: [{
field: "codeLong",
title: "codeLong"
},
{
field: "codeShort",
title: "codeShort"
},
{
field: "name",
title: "name"
}
]
});
}
alert("downlink-bulk-update");
console.log("downlink-bulk-update");
let that = this;
$(document).ready(function(){
$(".showHideIcon").click(function(){
alert("titleSearchResults");
});
});
this.kendocommand.model = {
id: "isSelected",
fields: {
contextRow: { editable: false },
isSelected: { type: "boolean", editable: true, filterable: false },
moduleName: { type: "string", editable: false },
entityId: { type: "string", filterable: true, editable: false, nullable: false },
entityName: { type: "string", editable: false, nullable: true },
network: { type: "string", editable: false },
entityType: { type: "string", editable: false },
userLocked: { type: "string", editable: false },
additionalComments: { type: "string", editable: false },
checkOutDate: { editable: false }
}
};
this.kendocommand.columns = [
{
field: 'contextRow',
width: 25, locked: true
},
{
field: "isSelected", filterable: false, sortable: false, editable: true, title: "Is Selected",
template: function (container) { return that.checkboxchecker(container, "isSelected") },
width: 30,
headerTemplate: '<span class="displayBlock"><input type="checkbox" id="unlockCheck" /></span>'
},
{
field: "moduleName",
title: "Module Name", filterable: that.gridkendo.getAutoFilterName("contains", "moduleName"), headerAttributes: { class: "multiCheckboxFilterEnabled" },
template: function moduleName(options) {
console.log("downlink-bulk-update 2");
return that.gridTemplate(options, "moduleName", false);
},
width: 150
}, {
field: "entityId", title: "ID",
filterable: that.gridkendo.getAutoFilterName("eq", "entityId"),
headerAttributes: { class: "multiCheckboxFilterEnabled" },
template: function entityId(options) {
console.log("ending this.kendocommand.columns");
return that.gridTemplate(options, "entityId", false);
},
width: 90
}, {
field: "entityName", filterable: that.gridkendo.getAutoFilterName("contains", "entityName"), headerAttributes: { class: "multiCheckboxFilterEnabled" },
template: function entityName(options) {
return that.gridTemplate(options, "entityName", false);
},
title: "Name",
width: 150
}, {
field: "network",
title: "Network",
filterable: that.gridkendo.getAutoFilterName("contains", "network"), headerAttributes: { class: "multiCheckboxFilterEnabled" },
template: function networkName(options) {
return that.gridTemplate(options, "network", false);
},
width: 110
}, {
field: "entityType",
title: "Type", filterable: that.gridkendo.getAutoFilterName("contains", "entityType"), headerAttributes: { class: "multiCheckboxFilterEnabled" },
template: function entityType(options) {
return that.gridTemplate(options, "entityType", false);
},
width: 150
}, {
field: "userLocked",
title: "User Locked", filterable: that.gridkendo.getAutoFilterName("contains", "userLocked"), headerAttributes: { class: "multiCheckboxFilterEnabled" },
template: function userLocked(options) {
return that.gridTemplate(options, "userLocked", false);
},
width: 150
}, {
field: "additionalComments",
title: "Additional Comments bulk", filterable: that.gridkendo.getAutoFilterName("contains", "additionalComments"), headerAttributes: { class: "multiCheckboxFilterEnabled" },
template: function additionalComments(options) {
return that.gridTemplate(options, "additionalComments", false);
},
width: 200
}, {
field: "checkOutDate",
title: "Date Checked Out", filterable: that.gridkendo.getAutoFilterName("contains", "checkOutDate"), headerAttributes: { class: "multiCheckboxFilterEnabled" },
template: function checkOutDate(options) {
return that.gridTemplate(options, "checkOutDate", false);
},
width: 200
}
];
console.log("ending this.kendocommand.columns");
}
private gridTemplate(options: any, fieldName: any, mandatory: any) {
console.log("gridTemplate downlink-bulk-update");
let value = options[fieldName];
if (options[fieldName] == null || options[fieldName] == undefined) {
value = "";
options[fieldName] = " ";
}
options[fieldName + "FilterRowId"] = value;
return value;
}
checkboxchecker(container, fieldName: any): any {
console.log("checkboxchecker downlink-bulk-update");
if ((this.selectedRowsUID.indexOf(container.uid) != -1) || this.selectAll) {
container.isSelected = true;
return '<input type="checkbox" checked="checked" style="display:block;" class="textAligncenter unlockCheckbox" #= fieldName ? \'checked="checked"\' : "false" #= fieldName/>';
} else {
this.count = true;
container.isSelected = false;
return '<input type="checkbox" style="display:block;" class="textAligncenter unlockCheckbox" #= fieldName ? \'checked="checked"\' : "false" #= fieldName/>';
}
}
}
‌
I suppose the 'options' problems occurs here:
var dropdown = $('#cars');
dropdown.options = function(data, selectedKey) ...
Well, this works in JavaScript, but the error the TypeScript compiler gives you is due to static type-checking. dropdown is here a jQuery object, and that type (assuming you're using type definitions for jQuery) does not declare a options property, so assigning to it generates an error. To allow TypeScript to do this, you must typecast to any, so the object behaves like any JavaScript object:
var dropdown: any = $('#cars');
dropdown.options = (...)
In the case of .Default it is the same error: you are declaring storedPreferences as
var storedPreferences = localStorage.getItem(...);
TypeScript knows that localStorage.getItem returns a string, so it considers storedPreferences to be of type string. In TypeScript you cannot change the type of a variable. In fact, it's the kind of thing it has been designed to prevent (as it is common in JavaScript and cause of frequent errors). TypeScript knows that string does not have a Default property and indicates an error.
To avoid this, again, you must declare storedPreferences to be of type any:
let storedPreferences: any = localStorage.getItem(...);
The problem is that you're programming in TypeScript as if it were JavaScript, and that's why you're getting compiler errors. In TypeScript you cannot add new properties to an object of a known type. To do this, you must previously declare the object as any, so TypeScript behaves exactly like JavaScript (though this way you lose TypeScript advantages).
Besides all this, you should avoid using var and use let or const instead.
The code in jsfiddle works, because that is JavaScript code, not TypeScript code.

EXTJS Window/Panel close error

I'm creating a new EXTJS window and inside that window there is a panel and inside that panel there is a form!
When I click on the 'X' or cancel to close the window I get this error:
Uncaught TypeError: Cannot read property 'className' of undefinedhasClass
# ext-all-debug.js:2252addClass
# ext-all-debug.js:2183Ext.Button.Ext.extend.onMouseOver
# ext-all-debug.js:31140aK
# miframe.js:1
I am using this handler in the cancel button:
handler: function () {
this.close();
},
Full code -
example.SurveyFieldDefaultWindow = Ext.extend(Ext.Window, {
id: 'survey-default-win',
title: 'Custom Survvey',
modal: true,
closable: true,
width: 500,
height: 600,
frame: true,
bodyStyle: 'padding: 5px',
forceFit: true,
constrainHeader: true,
layout: 'fit',
initComponent: function () {
this.canEdit = this.checkEditPermissions();
questionStore2 = questionStore;
var survey_window = Ext.getCmp('survey-win');
survey_window.afterRender(
survey_window.getFormValues()
);
formValues2 = formValuesObj;
survey_default_id = Math.floor(10000 + Math.random() * 90000);
Ext.apply(
this, {
items: [{
xtype: 'tabpanel',
id: 'survey-field-form-tabpanel',
layoutOnTabChange: true,
activeTab: 0,
items: [{
title: 'Questions',
layout: 'fit',
items: [{
xtype: 'form',
id: 'survey-field-form',
border: false,
bodyStyle: 'padding: 5px;',
frame: true,
defaultType: 'textfield',
}]
}]
}],
buttons: [{
id: 'save-button',
text: 'Default-Save',
handler: function () {
this.saveForm()
},
scope: this
}, {
text: 'Default-Cancel',
handler: function () {
this.close();
},
scope: this
}]
}
);
example.SurveyFieldDefaultWindow.superclass.initComponent.apply(this, arguments);
var data = questionStore2.data.items;
for (var i = 0; i < data.length; i++) {
if (data[i].data.fieldTypeName == "DropDownList" || data[i].data.fieldTypeName == "RadioButtonList" || data[i].data.fieldTypeName == "CheckBoxList" || data[i].data.fieldTypeName == "Rating" || data[i].data.fieldTypeName == "YesNo") {
// create a Record constructor:
var rt = Ext.data.Record.create([
{name: 'optionValue'},
{name: 'optionText'}
]);
var myStore = new Ext.data.Store({
// explicitly create reader
reader: new Ext.data.ArrayReader(
{
idIndex: 0 // id for each record will be the first element
},
rt // recordType
)
});
var myData = [];
for (var j = 0; j < data[i].data.selectOptions.list.length; j++) {
var optionText = data[i].data.selectOptions.list[j].optionText.toString();
var optionValue = data[i].data.selectOptions.list[j].optionValue.toString();
myData.push([optionValue, optionText]);
}
myStore.loadData(myData);
var id = data[i].data.name.toString();
var cb = new Ext.form.ComboBox({
fieldLabel: data[i].data.name,
id: id,
typeAhead: true,
allowBlank: true,
mode: 'local',
emptyText: 'Select Default value',
width: 190,
margin: '40 30 20 10',
store: myStore,
valueField: 'optionValue',
displayField: 'optionText',
selectOnFocus: true,
triggerAction: 'all',
listeners: {
'select': function (cb, newValue, oldValue) {
for (var i = 0; i < formValues2.fields.list.length; i++)
{
for (var j = 0; j < formValues2.fields.list[i].selectOptions.list.length; j++)
{
if(formValues2.fields.list[i].name == cb.fieldLabel ){
if( formValues2.fields.list[i].selectOptions.list[j].optionText == cb.lastSelectionText) {
formValues2.fields.list[i].selectOptions.list[j].preselect = true;
}
}
}
}
}
}
});
Ext.getCmp('survey-field-form').add(cb);
Ext.getCmp('survey-field-form').doLayout();
}
}
getDefaultSurveyFormValues = Ext.getCmp('survey-field-form');
getDefaultSurveyFormValues.on("afterrender", function () {
//this code will run after the panel renders.
if (getDefaultSurveyFormValues != undefined) {
getDefaultSurveyFormValues.getForm().getValues();
}
else {
console.log('undefined getDefaultSurveyFormValues');
}
});
},
checkEditPermissions: function () {
return Security.hasAccess("Surveys", Security.UPDATE_ACCESS);
},
saveForm: function () {
// disable save button while saving form
// Ext.getCmp('save-button').disable(); ----------------------------------- undo comment later
// submit the form using a jabsorb call
Ext.getCmp('survey-field-form').getForm().doAction("JabsorbSubmit", {
formValues: formValues2,
jabsorbMethod: Jabsorb.getInstance().surveyTemplateService.saveSurveyTemplate,
// timeout:300000,
failure: function (form, action) {
Ext.Msg.alert('Request Failed', 'Could not save survey template information to generate Survey View: ' + action.result.msg);
},
success: function (form, action) {
Ext.Msg.alert('magic' , 'magic');
}
});
}
});
Ext.reg('example.SurveyFieldDefaultWindow', example.SurveyFieldDefaultWindow);
I've made a fiddle, based on your code to create the window and using the close button. Check it here: https://fiddle.sencha.com/#fiddle/16lu
From what i've seen, in your initComponent: function() { you never call the this.callParent() method. It's very important for class inheritance if you use the initComponent config.
From the docs:
Call the "parent" method of the current method. That is the method
previously overridden by derivation or by an override (see
Ext.define).
In this scope, this represent the button and not the window, so you trying to close the button

Is there another event in ext.js I should use?

I have a column with text and an image. I am trying to add an event to the image. The id is assigned dynamically. When I try to bind the event, the Ext.get("id") is returning a null. I can see renderer running after viewready because the screen is refreshing. Should I try different DOM events?
{
text: 'My Thing',
flex: 6,
sortable: true,
width: 40,
dataIndex: 'myThing',
renderer: function (val, metaData, record, rowIdx, colIdx, store, view) {
{console.log(evname, arguments);});
var returnStr = '<div>' + val + '</div>' + '<img id="image_' + record.data.myItem.id + '" src="/myThing/img/icon.png"/>';
console.log(returnStr);
return returnStr;
}
console.log('Im here');
for(var j=0; j<items.length; j++){
console.log(j)
var itemDesc = 'image_' + items[j].data.myItem.id;
var itemDescStr = items[j].data.lineItem.myItem.id;
console.log('itemDesc' + itemDesc)
console.log(Ext.get(itemDesc));
(function(itemDescStr) {
Ext.get(itemDesc).on('click', function(e,t){
console.log('image '+ itemDescStr + ' clicked');
});
})(itemDescStr);
}
"Ext.get(itemDesc)" is returning a null.
Edit:
My temporary solution was this:
{
text: 'My Thing',
flex: 6,
sortable: true,
width: 40,
dataIndex: 'myThing'
renderer: function (val, metaData, record, rowIdx, colIdx, store, view) {
var returnStr = '<div><img id="image_' + record.data.myItem.id;
returnStr = returnStr + '" src="/myApp/resources/app/img/myIcon.gif" ';
returnStr = returnStr + 'onclick="Ext.foo(' + rowIdx + ')" />';
returnStr = returnStr + ' ' + val + '</div>';
return returnStr;
}
},
Don't do it like that, use event delegation:
Ext.onReady(function() {
var grid = new Ext.grid.Panel({
width: 400,
height: 400,
renderTo: document.body,
store: {
fields: ['name'],
data: [{
name: 'Foo'
}, {
name: 'Bar'
}]
},
columns: [{
dataIndex: 'name',
renderer: function(v) {
return Ext.String.format('<div class="x">{0}</div><div class="y">{0}</div><div class="z">{0}</div>', v);
}
}],
listeners: {
cellclick: function(view, el, cellIdx, record, row, rowIdx, e) {
if (e.getTarget('.x')) {
console.log('x');
} else if (e.getTarget('.y')) {
console.log('y');
} else {
console.log('neither');
}
}
}
});
});

Type Error when trying to preserve filter state - Kendo UI Grid

I'm working with Kendo UI's Grid and attempting to add some code which preserves the grid's filter/grouping/etc by way of a cookie. It works in the example, but not at all in my code.
Example: http://www.kendoui.com/code-library/web/grid/preserve-grid-state-in-a-cookie.aspx
My Code: http://jsfiddle.net/PwajE/
For whatever reason (I'm sure it's a simple one) I keep getting type errors. Two hours later... here I am.
As always, any help is appreciated.
#RRfive
<script>
var data = [{"name":"John Smith","email":"test#test.com","permission":"admin","costRate":"60","dt":"2013-02-02 10:26:29","memberID":"M0000001"},{"name":"Test Simple","email":"test#jones.com","permission":"user","costRate":"40","dt":"2013-02-02 00:00:00","memberID":"M0000002"}];
$(document).ready(function() {
$("#grid").kendoGrid({
dataSource: {
data: data,
//transport: {
// read: "assets/data/data.users.php",
//},
schema: {
data: function(result) {
return result.data || result;
},
total: function(result) {
var data = this.data(result);
return data ? data.length : 0;
},
model:{
id:"memberID",
fields:{
dt:{ type:"date" },
costRate:{ type:"number" }
}
}
},
pageSize: 10,
},
sortable: {
mode: "single",
allowUnsort: true,
},
pageable: {
input: true,
numeric: false
},
reorderable: true,
resizable: true,
filterable: {
extra:false,
operators: {
string:{
contains: "Contains",
}
}
},
columnMenu: false,
groupable: true,
dataBound: function(e){
var grid = this;
var dataSource = this.dataSource;
var state = kendo.stringify({
page: dataSource.page(),
pageSize: dataSource.pageSize(),
sort: dataSource.sort(),
group: dataSource.group(),
filter: dataSource.filter()
});
$.cookie("employeesState",state);
if($.cookie('empRows')){
$.each(JSON.parse($.cookie('empRows')),function(){
var item = dataSource.get(this);
var row = grid.tbody.find('[data-uid='+item.uid+']');
row.addClass('k-state-selected');
})
}
},
change:function(){
var grid = this;
var ids = grid.select().map(function(){
return grid.dataItem($(this)).Id
}).toArray();
$.cookie('empRows',JSON.stringify(ids));
},
columns: [
{ field: "name", title:"Name" },
{ field: "email", title:"Email/Username" },
{ field: "costRate", title:"Cost Rate (p/hr)", template: '#= kendo.toString(costRate, "c") #', },
{ field: "permission", title:"Permission", template: "#= (permission == 'admin') ? 'Administrator' : 'User' #" },
{ field: "dt", title:"Registered", template: '#= kendo.toString(dt,"d-M-yyyy") #' },
{ field: "memberID", title:" ", width: "83px", filterable: false, sortable: false, template: '<a class="k-button k-button-icontext k-grid-edit" href="manage_admin.php?form=editMember&ID=#= kendo.toString(memberID, "n2")#"><span class=\"k-icon k-edit\"></span>Edit</a>'},
]
});
var state = JSON.parse($.cookie("employeesState"));
if(state){
if(state.filter){
parseFilterDates(state.filter, grid.dataSource.options.schema.model.fields);
}
grid.dataSource.query(state);
}
else{
grid.dataSource.read();
}
});
function parseFilterDates(filter, fields){
if(filter.filters){
for(var i = 0; i < filter.filters.length; i++){
parseFilterDates(filter.filters[i], fields);
}
}
else{
if(fields[filter.field].type == "date"){
filter.value = kendo.parseDate(filter.value);
}
}
}
</script>
If you debug that fiddle you would see that the following line throws the error:
grid.dataSource.query(state);
The reason for this is that grid is not an instance of Kendo Grid but the div elemen with id='grid'. The fix is simple - initialize the grid variable prior to using it:
var grid = $("#grid").data('kendoGrid');
grid.dataSource.query(state);

Categories