Get values from a table cell - javascript

I have this part of code:
$.ig.loader(function () {
$("#grid2").igGrid({
autoGenerateColumns: false,
renderCheckboxes: true,
columns:[
{ headerText: "#", key: "#", dataType: "number", width: "40%"},
{ headerText: "filename", key: "fieldname", dataType: "image", width: "40%"},
{ headerText: "X", key: "x", dataType: "number", width: "40%"},
{ headerText: "Y", key: "y", dataType: "number", width: "40%"},
{ headerText: "Z", key: "z", dataType: "number", width: "40%"},
],
//dataSource: data,
height: "400px",
width: "100%",
features:[
{
name: "Filtering",
allowFiltering: true,
type: "local"
},
{
name: "Selection",
mode: "row"
},
{
name: "Updating",
enableAddRow: false,
editMode: "row",
// event raised after end row editing but before dataSource was updated
editCellEnding: function (evt, ui) {
// get cell’s checkbox value when it is changed
if (ui.update) {
if (ui.columnKey === "nid") {
logEvent("editCellEnded event fired. Column Key = " +
ui.columnKey + "; Row Index = " +
ui.rowID + "; Cell Value = " +
ui.value + "; Update = " +
ui.update);
}
}
},
enableDeleteRow: false,
columnSettings: [
{
columnKey: "#",
},
{
columnKey: "fieldname",
},
{
columnKey: "x",
},
{
columnKey: "y"
},
{
columnKey: "z"
}]
}
]
});
$.ajax({
type: "POST",
url: "http://cmsdemo.trueoffice.com/feature-json2",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
$("#grid2").igGrid({
dataSource: data
});
}
});
$("#grid2").live("iggridupdatingdatadirty", function (event, ui) {
$("#grid2").igGrid("commit");
return false;
});
// show the raised event
function logEvent(message) {
var evntWrap = $("#eventList");
$(evntWrap).append("<div>" + message + "<div>");
$(evntWrap).prop("scrollTop", $(evntWrap).prop("scrollHeight"));
}
});
//Functions
function Filter() {
var columnSettings = $("#grid1").igGridFiltering("option", "columnSettings");
var expr = $("#filterExpr").val(),
condition = $("#cond_list").val(),
filterColumn = $("#filterColumn").val();
$("#grid1").igGridFiltering("filter", ([{fieldName: filterColumn, expr: expr, cond: condition}]));
}
function SetConditions() {
var filterColumn = $("#filterColumn").val();
$("#cond_list option:selected").removeAttr("selected");
if (filterColumn === "title" || filterColumn === "nid") {
$("#cond_list .stringCondition").attr("disabled", "disabled");
$("#cond_list .numberCondition").removeAttr("disabled").eq(0).attr("selected", "selected");
}
else {
$("#cond_list .stringCondition").removeAttr("disabled").eq(0).attr("selected", "selected");
$("#cond_list .numberCondition").attr("disabled", "disabled");
}
}
function buttonClickHandler(buttonId) {
alert("Button with id " + buttonId + " was clicked");
}
and this part of code
<script>
var layer1 = document.getElementById('layer1');
ctx1 = layer1.getContext('2d');
var item1 = new Image();
item1.src = "<?php echo $base_url;?>/themes/bartik/images/sheep.png";
item1.addEventListener("load", function() {
ctx1.clearRect(0,0,1024,768)
ctx1.drawImage(item1,x,y)}, false); //how to get values from a table row?
</script>
My question is: How I can get values from a first row of table and send it to ctx1.drawImage(item1,x,y).
I can do copy/paste rest of the code if it be necessary.

Related

Using the content of a variable returned by DataTables in another part of the script

How can I use the "DeviceID" in the "columns:" in another part of the script. I have tried all manner of things like re positioning some of the code but no matter what I do I can't get it to work.
I need to use the "DeviceID" as a variable in
"url: 'get_wayfinder_offline_status.php', data: { DeviceID: deviceid },"
Look at << USE THIS IN PART MARKED "HERE"
$(document).ready(function() {
var table = $('#WayFinderStatusTable').DataTable({
ordering: false,
paging: false,
searching: false,
bInfo: false,
responsive: true,
fixedHeader: true,
scrollX: false,
pageResize: true,
ajax: {
url: 'check_wayfinder_status.php',
dataSrc: ''
},
columns: [{
data: 'DisplayDescription',
"sWidth": "100%"
},
{
data: 'DeviceName',
"visible": false
},
{
data: 'MessageCount',
"visible": false
},
{
data: 'BoardOverride',
"visible": false
},
{
data: 'DeviceID',
"visible": false
}, // << USE THIS IN PART MAKED "HERE"
],
rowCallback: function(row, data, dataIndex) {
if (data.MessageCount == 2) {
$(row).find('td:eq(0)').addClass('WayFinderStatusTableOn HeaderStatusWayfinderRedTextBlink');
} else if (data.BoardOverride == 1) {
$(row).find('td:eq(0)').addClass('WayFinderStatusTableOverrideOn ');
$('#WayFinderStatusTable tbody').on('click', 'tr', function() {
var hotelid = "<?php echo $_SESSION['_amember_user']['hotelid'];?>";
var data = table.row(this).data();
var deviceid = data.DeviceID;
console.log("DEVICE ID", deviceid);
$.ajax({
url: 'get_wayfinder_override_status.php',
data: {
DeviceID: deviceid
},
type: 'POST',
dataType: 'JSON',
success: function(data) {
var result = JSON.stringify(data);
result = JSON.parse(result);
if (result.length > 0) {
console.log("BoardName", result);
$('#EditOverrideWayfinderRecordID').val(result[0]);
$('#EditOverrideWayfinderBoardName').val(result[1]);
var testimage = result[2];
console.log("TEST IMAGE", testimage);
$('#EditOverrideWayfinderImage').val(result[2]);
var imagepath = '../../../../conf/conf_images/override/' + hotelid + '/' + result[2];
$("#EditOverrideWayfinderLookUpCompanyImage").attr("src", imagepath);
$("#EditOverrideWayfinderImagePreview").attr("src", imagepath);
$('#EditOverrideWayfinderRoomFromDate').val(result[3]);
$('#EditOverrideWayfinderRoomFromTimeH').val(result[4]);
$('#EditOverrideWayfinderRoomFromTimeM').val(result[5]);
$('#EditOverrideWayfinderRoomToDate').val(result[6]);
$('#EditOverrideWayfinderRoomToTimeH').val(result[7]);
$('#EditOverrideWayfinderRoomToTimeM').val(result[8]);
$('#EditOverrideWayfinderPromotionName').val(result[9]);
$('#EditOverrideWayfinderHardwareID').val(result[10]);
$('#edit_wayfinder_override_data_modal').modal('show');
}
}
});
});
} else if (data.BoardOverride == "") {
$(row).find('td:eq(0)').addClass('WayFinderStatusTableOff');
}
},
});
$(document).on('click', '.WayFinderStatusTableOff', function(e) {
$('#wayfinder_override_data_modal').modal('show');
});
$(document).on('click', '.WayFinderStatusTableOn', function(e) {
console.log("OFFLINE CLICKED");
$.ajax({
url: 'get_wayfinder_offline_status.php',
data: {
DeviceID: deviceid //<<HERE
},
type: 'POST',
dataType: 'JSON',
success: function(data) {
var result = JSON.stringify(data);
result = JSON.parse(result);
if (result.length > 0) {
// DO SOMETHING
}
}
});
$('#offline_data_modal').modal('show');
});
setInterval(function() {
$('#WayFinderStatusTable').DataTable().ajax.reload();
}, 30000);
});
Based on structure of your datatables and column, clicked on a row the deviceId is find by using the method table.row( this ).data(); and next find the right index of the data.
$('#WayFinderStatusTable').on('click', 'tr', function () {
const data = table.row( this ).data();
const deviceId = data[4];
alert(deviceId + ' -> deviceid');
});

How to remove all items from a kendoListBox

I have two kendo list boxes they exchange items between them. Basically an Items available and an Items selected pair.
I have Json service which controls what items are available via a Json array.
When the user selects a new filter I want both Kendo List Boxes to clear the items out before adding the new items from the server.
Currently it appends the new list from the server to the current list.
$(document).ready(function () {
$("#filterKeyWord").click(function () {
getResults($("#keywords"));
});
$("#availableReports").kendoListBox({
dataTextField: "Name",
dataValueField: "ID",
connectWith: "selectedReports",
dropSources: ["availableReports"],
toolbar: {
tools: ["transferTo", "transferFrom", "transferAllTo", "transferAllFrom", "remove"]
}
});
$("#selectedReports").kendoListBox({
dataTextField: "Name",
dataValueField: "ID",
dropSources: ["selectedReports"],
remove: function (e) {
setSelected(e, false);
},
add: function (e) {
setSelected(e, true);
}
});
var mydata = { ReportName: "", UserId: "" };
mydata.ReportName = "SomeName";
mydata.UserId = "SomeUser";
var crudService = "",
dataSource = new kendo.data.DataSource({
serverFiltering: true,
transport: {
read: {
url: crudService + "GetReportList",
dataType: "json",
type: "get",
contentType: "application/json; charset=utf-8",
},
update: {
url: crudService + "SaveReportList2",
dataType: "json",
contentType: "application/json; charset=utf-8",
type: "post",
},
filter: {
url: crudService + "GetReportList",
dataType: "json",
type: "get",
contentType: "application/json; charset=utf-8",
},
parameterMap: function (options, operation) {
console.log(operation);
if (operation !== "read" && options.models) {
return JSON.stringify({ models: options.models });
}
if (operation === "read") {
return "request=" + JSON.stringify(mydata);
}
}
},
batch: true,
requestStart: function () {
kendo.ui.progress($(".demo-section"), true);
console.log("request start");
},
requestEnd: function () {
kendo.ui.progress($(".demo-section"), false);
console.log("request end");
},
error: function (e) {
console.log("Error" + e);
},
change: function (e) {
console.log("change" + this.data.length);
setDropDownBoxes(this);
},
schema: {
model: {
id: "ID",
fields: {
ID: { type: "number" },
Selected: { type: "boolean" },
Name: { type: "string" },
Description: { type: "string" },
InternalId: { type: "string" }
}
}
}
});
$("#saveReportList").kendoButton({
click: function (e) {
dataSource.sync();
}
});
$("#getReportList").kendoButton({
click: function (e) {
mydata.ReportName = $("#keywords").val();
dataSource.read();
}
});
function setDropDownBoxes(obj) {
var data = obj.data();
var availableReports = $("#availableReports").data("kendoListBox");
var selectedReports = $("#selectedReports").data("kendoListBox");
var items = availableReports.dataItems();
for (var i = 0; i < data.length; i++) {
if (data[i].Selected) {
selectedReports.add(data[i]);
}
else {
availableReports.add(data[i]);
}
}
}
function setSelected(e, flag) {
var removedItems = e.dataItems;
for (var i = 0; i < removedItems.length; i++) {
console.log(flag + " " + removedItems[i].ID + " " + removedItems[i].Name + " " + removedItems[i].Selected);
var item = dataSource.get(removedItems[i].ID);
item.Selected = flag;
item.dirty = !item.dirty;
}
}
});
Not sure where in your exactly the clening should be performed, but, you can use both remove() and item() methods togheter to clear a listBox.
remove() method accepts a list of li elements, which is what items() returns, so it will remove the whole li collection from the list.
var listBox = $("#listBox").data("kendoListBox");
listBox.remove(listBox.items());
Demo

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.

Kendo treelist Child node issue

whenever i cancelled the updating process from the child node,the child node just merge with root node,i don't find error in the console or i can't find anything suspicious.but after a reload,all becomes normal
$(document).ready(function () {
var windowTemplate = kendo.template($("#windowTemplate").html());
var dataSource = new kendo.data.TreeListDataSource({
transport: {
read: {
url: "officeprofiletree",
type: 'POST',
dataType: "json"
},
update: {
url: "officeprofilenametree_update",
type: 'POST',
contentType :'application/json',
dataType: "json"
},
destroy: {
url: "officeprofilenametree_destroy",
type: 'POST',
contentType :'application/json',
dataType: "json"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models)
{
return JSON.stringify(options.models);
}
}
},
batch: true,
sort: { field: "name", dir: "asc" },
schema: {
model: {
id: "officeProfileNMId",
parentId: "parentId",
fields: {
officeProfileNMId: { type:"number" },
parentId:{nullable:true,type:"number"},
mobile:{ type:"string"},
address:{type:"string"},
phone: {type:"string"},
},
}
}
});
var window = $("#window").kendoWindow({
visible:false,
title: "Are you sure you want to delete this record?",
width: "450px",
height: "60px",
}).data("kendoWindow");
var treelist = $("#treelist").kendoTreeList({
dataSource: dataSource,
pageable: true,
dataBound: function (){
var tree = this;
var trs = this.tbody.find('tr').each(function(){
var item = tree.dataItem($(this));
if( item.parentId == null) {
$(this).find('.k-button,.k-button').hide();
}
});
},
columns: [
{ field: "name", title: "Name"},
{ field: "mobile", title:"Mobile", format: "{0:c}", hidden: true },
{ field: "address", title:"Address",hidden: true },
{ field: "phone",title:"Phone" ,hidden: true },
{ command: [
{name: "edit"},
{name: "Delete",
click: function(e){
e.preventDefault();
var tr = $(e.target).closest("tr");
var data = this.dataItem(tr);
window.content(windowTemplate(data));
window.center().open();
$("#yesButton").click(function(){
treelist.dataSource.remove(data);
treelist.dataSource.sync();
window.close();
reloading();
})
$("#noButton").click(function(){
window.close();
})
}
}
]}
] ,
editable: {
mode: "popup",
},
}).data("kendoTreeList");
});
the updation and deletion works fine by the way,Here is the fiddle
https://jsfiddle.net/me09jLy7/2/
updation:
whenever i create a child to ranikannur gives me 3 children with same name in each root ranikannur,in my database there is only one child is parented by ranikannur but treelist shows it as 3 children in each parent node,the children count 3 is getting from the total ranikannurparent nodes(here tree has 3 ranikannur parent nodes)
i guess.how is this getting the 3 children?
u just try it...
$(document).ready(function () {
var windowTemplate = kendo.template($("#windowTemplate").html());
var dataSource = new kendo.data.TreeListDataSource({
transport: {
read: {
url: "officeprofiletree",
type: 'POST',
dataType: "json"
},
update: {
url: "officeprofilenametree_update",
type: 'POST',
contentType :'application/json',
dataType: "json"
},
destroy: {
url: "officeprofilenametree_destroy",
type: 'POST',
contentType :'application/json',
dataType: "json"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models)
{
return JSON.stringify(options.models);
}
}
},
batch: true,
sort: { field: "name", dir: "asc" },
schema: {
model: {
id: "officeProfileNMId",
parentId: "parentId",
fields: {
officeProfileNMId: { type:"number" },
parentId:{nullable:true,type:"number"},
mobile:{ type:"string"},
address:{type:"string"},
phone: {type:"string"},
},
}
}
});
var window = $("#window").kendoWindow({
visible:false,
title: "Are you sure you want to delete this record?",
width: "450px",
height: "60px",
}).data("kendoWindow");
var treelist = $("#treelist").kendoTreeList({
dataSource: dataSource,
pageable: true,
dataBound: function (){
var tree = this;
var trs = this.tbody.find('tr').each(function(){
var item = tree.dataItem($(this));
if( item.parentId == null) {
$(this).find('.k-button,.k-button').hide();
}
});
},
columns: [
{ field: "name", title: "Name"},
{ field: "mobile", title:"Mobile", format: "{0:c}", hidden: true },
{ field: "address", title:"Address",hidden: true },
{ field: "phone",title:"Phone" ,hidden: true },
{ command: [
{name: "edit"},
{name: "Delete",
click: function(e){
e.preventDefault();
var tr = $(e.target).closest("tr");
var data = this.dataItem(tr);
window.content(windowTemplate(data));
window.center().open();
$("#yesButton").click(function(){
treelist.dataSource.remove(data);
treelist.dataSource.sync();
window.close();
reloading();
})
$("#noButton").click(function(){
window.close();
})
}
}
]}
] ,
editable: {
mode: "popup",
},
}).data("kendoTreeList");
});

Kendo Scheduler, programmatically set values not updating dataModel

Kendo Scheduler via javascript
Custom Edit Template
Edit Event -> programmatically setting a value on custom template controls
Value shows in control, not included in dataModel
I am implementing a Kendo Scheduler via javascript. I am using a custom edit template because there are several editable fields which are not native to the scheduler. One such field uses a kendo dropdownlist. I have subscribed to the edit event and in this event I get a handle on the dropdown and set its value. The UI element correctly shows the value I have set but when I save the scheduler the dropdownlist value is not included in the JSONified dataModel which I pass off to a CRUD handler. If I manually select an option from the dropdownlist it is included. I called the change event of the dropdownlist for giggles after the programmatic setting of its value. Still nothing. I tried this with textboxes, multiselections, numerictextboxes... they all fail to register their programmatically set values with the model.
Ideas? Thanks.
$(function () {
$("#scheduler").kendoScheduler({
date: new Date("2015/4/14"),
views: [
"day",
{ type: "workWeek", selected: true, showWorkHours: true },
"week",
"month"
],
allDayEventTemplate: $("#allDay-template").html(),
eventTemplate: $("#event-template").html(),
edit: function (e) {
var location = e.container.find("[id=location]");
location.kendoComboBox({
dataTextField: "text",
dataValueField: "value",
dataSource: GetLocations,
filter: "contains",
suggest: true
});
var taskReminder = e.container.find("[id=AddTaskReminder]");
taskReminder.kendoNumericTextBox({
placeholder: "None",
format: "n0",
min: "0",
decimals: "0",
step: 15
});
var wnd = $(e.container).data("kendoWindow");
wnd.setOptions({
width: 800,
height: 600
});
var clientID = $("#clientID");
var ClientID = e.container.find("[id=ClientID]").data("kendoDropDownList");
if (clientID.val() != "All") {
ClientID.enable(false);
}
var Priority = $(e.container.find('[data-bind="value: Priority"]')).data("kendoDropDownList");
if (e.event.isNew()) {
if (clientID.val() != "All") {
ClientID.value(clientID.val());
e.container.find("[id=ClientID]").change();
}
var workerID = $("#workerID");
var WorkerID = e.container.find("[id=workers]").data("kendoMultiSelect");
if (workerID.val() != null) {
WorkerID.value(workerID.val());
e.container.find("[id=workers]").change();
}
Priority.value(2);
(e.container.find('[data-bind="value: Priority"]')).change();
}
var taskName = e.container.find("[id=taskName]");
taskName.kendoComboBox({
dataSource: GetTaskTypes,
dataTextField: "text",
dataValueField: "value",
filter: "contains",
suggest: true
});
var isAllDay = $(e.container.find('[id=isAllDay]'));
var StartDateTime = $(e.container.find('[id=startdatetime]')).data("kendoDateTimePicker");
var EndDateTime = $(e.container.find('[id=enddatetime]')).data("kendoDateTimePicker");
var DueDateFirm = $(e.container.find('[id=DueDateFirm]'));
var Reminder = $(e.container.find('[id=AddTaskReminder]')).data("kendoNumericTextBox")
var TaskComment = $(e.container.find('[id=TaskComment]'));
taskName.change(function () {
$("#TaskTypeName").val($(e.container.find("[id=taskName]")).data("kendoComboBox").text());
if ($(e.container.find("[id=taskName]")).data("kendoComboBox").select() != "-1") {
if (confirm("Apply task type defaults (overriding previous values)?")) {
$.ajax({
type: "GET",
cache: false,
url: "/home/schedule/remotetasks.asp?Action=GetDefaultTaskTypeValues&DefaultTask=" + $(taskName).val(),
success: function (data) {
DS = JSON.parse(data);
Priority.value(DS[0].Priority);
if (DS[0].AllDayEvent == "True") {
isAllDay.prop("checked", true);
}
else {
isAllDay.prop("checked", false);
if (DS[0].DefaultStartTime != "") {
var d = new Date(StartDateTime.value());
d.setHours(DS[0].DefaultStartHour);
d.setMinutes(DS[0].DefaultStartMinute);
StartDateTime.value(d);
}
if (DS[0].DefaultEndTime != "") {
var d = new Date(EndDateTime.value());
d.setHours(DS[0].DefaultEndHour);
d.setMinutes(DS[0].DefaultEndMinute);
EndDateTime.value(d);
}
}
isAllDay.change();
Reminder.value(DS[0].DefaultReminderMinutes);
TaskComment.val(DS[0].TaskComment);
}
});
}
}
});
},
save: function (e) {
if (e.container != null) {
// AssignedTaskName req val
// Dates req val
var isAllDay = e.container.find("[id=isAllDay]");
var startdatetime = e.container.find("[id=startdatetime]");
var startdate = e.container.find("[id=startdate]");
var enddatetime = e.container.find("[id=enddatetime]");
var startdatereq = e.container.find("[id=startdatereq]");
var enddatereq = e.container.find("[id=enddatereq]");
var isAllDay = $(startdate).is(":visible");
if (isAllDay) {
if ($(startdate).val() == "") {
//alert('invalid startdate');
e.preventDefault();
if ($(startdatereq).hasClass('hidden'))
startdatereq.removeClass('hidden');
}
else {
//alert('valid startdate');
if (!$(startdatereq).hasClass('hidden'))
startdatereq.addClass('hidden');
}
}
else {
if ($(startdatetime).val() == "") {
//alert('invalid startdatetime');
e.preventDefault();
if ($(startdatereq).hasClass('hidden'))
startdatereq.removeClass('hidden');
}
else {
//alert('valid startdatetime');
if (!$(startdatereq).hasClass('hidden'))
startdatereq.addClass('hidden');
}
if ($(enddatetime).val() == "") {
//alert('invalid enddatetime');
e.preventDefault();
if ($(enddatereq).hasClass('hidden'))
enddatereq.removeClass('hidden');
}
else {
//alert('valid enddatetime');
if (!$(enddatereq).hasClass('hidden'))
enddatereq.addClass('hidden');
}
}
}
},
editable: {
template: kendo.template($("#customEditorTemplate").html())
},
moveEnd: function (e) {
if (!confirm("Are you sure you want to update this event?")) {
e.preventDefault();
}
},
resizeEnd: function (e) {
if (!confirm("Are you sure you want to update this event?")) {
e.preventDefault();
}
},
dataSource: {
batch: true,
sync: function () {
this.read();
},
transport: {
create: {
url: "/home/schedule/remotemanagecalendar.asp?Action=create",
dataType: "json"
},
read: {
url: "/home/schedule/remotemanagecalendar.asp?Action=read",
dataType: "json"
},
update: {
url: "/home/schedule/remotemanagecalendar.asp?Action=update",
dataType: "json"
},
destroy: {
url: "/home/schedule/remotemanagecalendar.asp?Action=destroy",
dataType: "json"
},
parameterMap: function (options, operation) {
if (operation === "read") {
var scheduler = $("#scheduler").data("kendoScheduler");
var result = {
start: scheduler.view().startDate(),
end: scheduler.view().endDate(),
clientid: $("#clientID").val(),
workerid: $("#workerID").val(),
taskstatus: $("#taskStatus").val()
}
return { models: kendo.stringify(result) };
}
else if (operation === "create" && options.models) {
return { models: kendo.stringify(options.models) + "||" + $("#TaskTypeName").val() };
}
else if (operation === "update" && options.models) {
return { models: kendo.stringify(options.models) + "||" + $("#TaskTypeName").val() };
}
else if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
schema: {
model: {
id: "id",
fields: {
id: { from: "AssignedTaskID", type: "number" },
taskTypeID: { from: "TaskTypeID", type: "int" },
title: { from: "AssignedTaskName", type: "string" },
start: { from: "StartDateTime", type: "date", validation: { required: true } },
end: { from: "EndDateTime", type: "date" },
isAllDay: { from: "isAllDay", type: "boolean" },
dueDateFirm: { from: "DueDateFirm", type: "boolean" },
reminderMinutes: { from: "ReminderMinutes", type: "int" },
ClientID: { from: "ClientID", type: "int" },
Priority: { from: "Priority", type: "int" },
workers: { from: "Workers", nullable: true },
TaskComment: { from: "TaskComment", type: "string" },
locationid: { from: "LocationID", type: "string" }
}
}
}
}
});
});
var GetTaskTypes = new kendo.data.DataSource({
transport: {
read: {
url: "/home/schedule/remotetasks.asp?Action=GetAddTaskTypes",
dataType: "json"
}
}
});
var GetClientIDs = new kendo.data.DataSource({
transport: {
read: {
url: "/home/schedule/remotetasks.asp?Action=GetAddClients",
dataType: "json"
}
}
});
var GetPriorities = new kendo.data.DataSource({
transport: {
read: {
url: "/home/schedule/remotemanagecalendar.asp?Action=GetPriorities",
dataType: "json"
}
}
});
var GetAddWorkers = new kendo.data.DataSource({
transport: {
read: {
url: "/home/schedule/remotetasks.asp?Action=GetAddWorkers",
dataType: "json"
}
}
});
var GetLocations = new kendo.data.DataSource({
transport: {
read: {
url: "/home/schedule/remotemanagecalendar.asp?Action=GetLocations",
dataType: "json"
}
}
});
$("#AddTaskReminder").kendoNumericTextBox({
placeholder: "None",
format: "n0",
min: "0",
decimals: "0",
step: 15
});
I found the answer
edit: function(e) {
e.event.set('modelFieldName', 'value');
}
This sets it on the UI element as well as updates the dataModel. Hope it helps the next poor sap.

Categories