I am using jsgrid with checkboxes for row selection such as below
$(function() {
$("#jsGrid").jsGrid({
...
headerTemplate: function() {
return $("<input>").attr("type", "checkbox").attr("id", "selectAllCheckbox");
},
itemTemplate : function(_, item) {
return $("<input>").attr("type", "checkbox").attr("class", "singleCheckbox")
.prop("checked", $.inArray(item, selectedItems) > -1)
.on("change", function () {
$(this).is(":checked") ? selectItem(item) : unselectItem(item);
});
},
}
fields :[{
{ name: "unique_id", type: "text", width: 100, visible:false },
{ name: "some_name", type: "text", width: 100},
...
]
});
$("#selectAllCheckbox").click(selectAllCheckBox);
});
The selectAllCheckBox function given below.
var selectAllCheckBox = function(item) {
selectedItems = [];
if(this.checked) { // check select status
$('.singleCheckbox').each(function() {
this.checked = true;
selectItem($(this).parent().next().text());//line 1
});
}else {
$('.singleCheckbox').each(function() {
this.checked = false;
unselectItem(item);
});
selectedItems = [];
}
}
I would like to collect all the selected unique_ids and process it on the server side. But, as unique_id is hidden, the code at line 1 always returns the values of some_name. How can I get the values of unique_id?
In jsGrid docs, I have not found any method regarding or getting hidden column but you can do like below manually implementation to get the selected record/id.
I have taken a custom selections config inside of jsGrid object as array to store the selected row into that.
*I am pushing full object of particular record in selections array inside of jsGrid.
DEMO
$("#jsGrid").jsGrid({
width: "100%",
paging: true,
selections: [],
data: [{
ClientId: 1,
Client: "Aaaa Joseph"
}, {
ClientId: 2,
Client: "Zzzz Brad"
}, {
ClientId: 3,
Client: "Mr Nice Guy"
}],
fields: [{
headerTemplate: function() {
var grid = this._grid;
return `<input class="all" type="checkbox" ${grid.selections.length==grid.data.length?'checked':''} />`;
},
itemTemplate: function(_, item) {
return `<input class="single" value=${item.ClientId} type="checkbox" _isall=${false} ${this._grid.selections.some(ClientId=>ClientId==item.ClientId)?'checked':''} />`
}
}, {
type: "text",
width: 80,
name: 'Client'
}]
});
$('#jsGrid input[type=checkbox]').on('change', function() {
var checkbox = $(this),
grid = checkbox.closest('#jsGrid').data().JSGrid;
if (checkbox.attr('class') == 'all') {
let checked = checkbox.is(":checked");
grid.selections = checked ? grid.data : [];
$.each($('#jsGrid input[class=single]'), (i, el) => $(el).prop('checked', checked))
} else {
if (checkbox.is(":checked")) {
grid.selections.push(grid.data.find(({
ClientId
}) => ClientId == checkbox.val()));
} else {
grid.selections = grid.selections.filter(({
ClientId
}) => ClientId != checkbox.val());
}
checkbox.closest('#jsGrid').find('input.all').prop('checked', grid.selections.length == grid.data.length);
}
});
$('button.getrecord').on('click', function() {
console.clear();
console.log($('#jsGrid').data().JSGrid.selections);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.css" />
<link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid-theme.min.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.js"></script>
<button class="getrecord">Get Selected record</button>
<div id="jsGrid"></div>
This is not answer.. i cant add the code in above comment, that has a related question. so adding it here.. what is wrong with this code. grid not loading. I am using adminLte plugin jsgrid in
https://adminlte.io/themes/v3/pages/tables/jsgrid.html
<script>
$("#jsGrid").jsGrid({
width: "100%",
paging: true,
selections: [],
controller: {
loadData: function() {
var d = $.Deferred();
$.ajax({
type: 'GET',
url: 'https://xkcd.com/info.0.json',
dataType: "json",
success: function (data) {
d.resolve(data);
},
error: function(e) {
alert("error: " + e.responseText);
}
});
console.log("here test");
return d.promise();
}
},
fields: [{
headerTemplate: function() {
var grid = this._grid;
return `<input class="all" type="checkbox" ${grid.selections.length==grid.loadData.length?'checked':''} />`;
},
itemTemplate: function(_, item) {
return `<input class="single" value=${item.num} type="checkbox" _isall=${false} ${this._grid.selections.some(num=>num==item.num)?'checked':''} />`
},
width: 10,
align: "center"
}, { name: "year", type: "textarea", title: "year", width: 50 },
{ name: "month", type: "number", title: "month", width: 50, align: "center" },
{ name: "day", type: "number", title: "day", width: 50 , align: "center"},
{ name: "title", type: "textarea", title: "title", width: 50 , align: "center"}]
});
$('#jsGrid input[type=checkbox]').on('change', function() {
var checkbox = $(this),
grid = checkbox.closest('#jsGrid').data().JSGrid;
if (checkbox.attr('class') == 'all') {
let checked = checkbox.is(":checked");
grid.selections = checked ? grid.data : [];
$.each($('#jsGrid input[class=single]'), (i, el) => $(el).prop('checked', checked))
} else {
if (checkbox.is(":checked")) {
grid.selections.push(grid.data.find(({
feed_id
}) => feed_id == checkbox.val()));
} else {
grid.selections = grid.selections.filter(({
feed_id
}) => feed_id != checkbox.val());
}
checkbox.closest('#jsGrid').find('input.all').prop('checked', grid.selections.length == grid.data.length);
}
});
$('button.getrecord').on('click', function() {
console.clear();
console.log($('#jsGrid').data().JSGrid.selections);
});
</script>
Related
I have a Kendo Grid with checkbox selection in my MVC web application. I am trying to set some initial selections that trigger on databind. Here is my grid code:
#(Html.Kendo().Grid<MyProject.ViewModels.MyViewModel>()
.Name("MyGrid")
.Columns(columns => {
columns.Select().Width(50);
columns.Bound(c => c.Id);
columns.Bound(c => c.Name).Title("Name")
})
.Pageable()
.Sortable()
.Events(ev => ev.DataBound("onChange"))
.PersistSelection()
.DataSource(dataSource => dataSource
.Ajax()
.Model(model => model.Id(p => p.Id))
.Read(read => read.Action("GetData", "Test"))
))
You'll notice that under the events parameter I've set a function to trigger on DataBound called onChange. This function is where I want to make my initial selections. I started writing a function to achieve this and Telerik assisted with some code:
function onChange(e) {
//Sample array
var arr = [206, 210];
for (var i = 0; i < e.sender.items().length; i++) {
//206 is a test value, I want to pass an array in.
if (e.sender.dataItem(e.sender.items()[i]).Id == 206) {
e.sender.select(e.sender.items()[i]);
}
}
}
This code only takes me part of the way. What I want to do and where I need help is, adjusting this code to accept an array of Ids and select those items. For testing purposes, I have made a very basic array called arr but I'm not sure how to pass this into the loop.
I attempted to get it working using a jquery each loop to iterate over every value in the array and select the row but it didn't work. The code was something like:
function onChange(e) {
//Sample array
var arr = [206, 210];
$.each(arr, function(i, v) {
if (e.sender.dataItem(e.sender.items()[i]).Id == v) {
e.sender.select(e.sender.items()[i]);
}
})
}
Any help is appreciated.
Use indexOf() to check if each Id exists in the array:
function onChange(e) {
//Sample array
var arr = [206, 210],
grid = e.sender;
for (var i = 0; i < grid.items().length; i++) {
if (arr.indexOf(grid.dataItem(grid.items()[i]).Id) > -1) {
grid.select(grid.items()[i]);
}
}
}
Working example:
let arr = [1,3,5,7],
data = [1,2,3,4,5,6,7,8,9,10];
for (let i = 0, len = data.length; i < len; i++) {
if (arr.indexOf(data[i]) > -1) {
console.log(`item ${data[i]} exists in the array`);
}
}
Here I have a namespaced myApp with functions where I added a klookup function to return the first match in an array, then select using that. Note I used the dataBound event using a kendo data sample.
// create a namespace for my functions
var myApp = myApp || {};
myApp.funcs = {
klookup: function(myArray, searchTerm, property, firstOnly) {
var found = [];
var i = myArray.items().length;
while (i--) {
if (myArray.dataItem(myArray.items()[i])[property] == searchTerm) {
found.push(myArray.items()[i]);
if (firstOnly) break; //if only the first
}
}
return found;
},
onDataBound: function(e) {
// console.log("onDataBound");
myApp.data.Sender = e.sender;
let s = myApp.data.Sender
// console.dir(myApp.data.arr);
let rows = s.items();
//console.log(rows);
myApp.data.arr.forEach(function(entry) {
let found = myApp.funcs.klookup(s, entry, "OrderID", true);
s.select(found[0]);
});
}
};
// add data to my namespace
myApp.data = {
arr: [10248, 10250]
};
$(function() {
$("#grid").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Orders"
},
schema: {
model: {
fields: {
OrderID: {
type: "number"
},
Freight: {
type: "number"
},
ShipName: {
type: "string"
},
OrderDate: {
type: "date"
},
ShipCity: {
type: "string"
}
}
}
},
pageSize: 5,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
persistSelection: true,
dataBound: myApp.funcs.onDataBound,
height: 550,
filterable: true,
sortable: true,
pageable: true,
columns: [{
selectable: true,
width: "50px"
}, {
field: "OrderID",
filterable: false
},
"Freight",
{
field: "OrderDate",
title: "Order Date",
format: "{0:MM/dd/yyyy}"
}, {
field: "ShipName",
title: "Ship Name"
}, {
field: "ShipCity",
title: "Ship City"
}
]
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.2.620/styles/kendo.common.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.2.620/styles/kendo.blueopal.min.css" />
<script src="https://kendo.cdn.telerik.com/2018.2.620/js/kendo.all.min.js"></script>
<div id="grid"></div>
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.
I've got a Kendo Grid and on its DataBound event, I want to add its data source to a Kendo MultiSelect. So, when the data from the grid is loaded, the below function is fired.
Here's what I have tried so far, without success, but from the code you can see what I intend:
function addToMultiSelect() {
var multiSelect = $("#multiSelect").data("kendoMultiSelect");
var grid = $("#grid").data("kendoGrid");
var places = grid.dataSource._data;
for (var i = 0; i < places.length; i++) {
var row = instPlaces[i];
var id = row.Id;
var mediumDescription = row.MediumDescription;
alert(id + " - " + mediumDescription);
multiSelect.dataSource.insert(i, { text: mediumDescription, value: id })
}
multiSelect.dataSource.read();
}
The alert properly shows the id and description of all the datagrid's items, so, I'm getting the data from the grid right.
I add them to the multiSelect's datasource, the last line is to refresh it and show the new data, but it doesn't. The multiSelect remains empty.
Try the following:
function addToMultiSelect() {
var multiSelect = $("#multiSelect").data("kendoMultiSelect");
var grid = $("#grid").data("kendoGrid");
var places = grid.dataSource.data();
// Read original data content
var multiData = multiSelect.dataSource.data();
for (var i = 0; i < places.length; i++) {
...
// insert new element into copy of multiselect data
multiData.push({ text: mediumDescription, value: id })
}
// Write back the modified data
multiSelect.dataSource.data(multiData);
}
See the following code example:
$(document).ready(function() {
function addToMultiSelect(e) {
var grid = this;
var data = this.dataSource.data();
var multiData = [];
for (var i = 0; i < data.length; i++) {
multiData.push({ text: data[i].ShipName, value: i });
}
multi.dataSource.data(multiData);
}
var multi = $("#multi").kendoMultiSelect({
dataSource: {
data: [
{ text: "ship 1", value: 1 },
{ text: "ship 2", value: 2 },
{ text: "ship 3", value: 3 },
{ text: "ship 4", value: 4 }
]
},
dataTextField: "text",
dataValueField: "value"
}).data("kendoMultiSelect");
$("#grid").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "http://demos.telerik.com/kendo-ui/service/Northwind.svc/Orders"
},
schema: {
model: {
fields: {
OrderID: { type: "number" },
Freight: { type: "number" },
ShipName: { type: "string" },
OrderDate: { type: "date" },
ShipCity: { type: "string" }
}
}
},
pageSize: 20,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
dataBound: addToMultiSelect,
height: 550,
columns: [
"OrderID",
"Freight",
{
field: "OrderDate",
title: "Order Date",
format: "{0:MM/dd/yyyy}"
},
{
field: "ShipName",
title: "Ship Name"
},
{
field: "ShipCity",
title: "Ship City"
}
]
});
});
html { font-size: 12px; font-family: Arial, Helvetica, sans-serif; }
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1316/styles/kendo.common.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1316/styles/kendo.default.min.css" />
<script src="http://cdn.kendostatic.com/2014.3.1316/js/jquery.min.js"></script>
<script src="http://cdn.kendostatic.com/2014.3.1316/js/kendo.all.min.js"></script>
Ship Names copied from Grid DataSource: <input id="multi"/>
Grid
<div id="grid"></div>
I have a Kendo UI Grid that displays n-child records, that I also have a custom resize function that keeps the grid sized for the browser window height. If I remove that resizeListener, the child records display as appropriate. If I have the resizeListener bound, the child records do not display.
This issue is specific to Internet Explorer 8 (sorry, it's a company policy limitation). The grid functions normally in Firefox.
I have tried using $(window).off("resize") when I activate the child template, in the databound, and in really a variety of random places that I thought might possibly work - but nothing so far.
I'm looking for a solution or a work-around for IE.
Here is the function:
function resizeGrid() {
var gridElement = $("#boxesgrid");
var dataArea = gridElement.find(".k-grid-content");
var newGridHeight = $(document).height() > 850 ? 850 : $(document).height() * .75;
var newDataAreaHeight = newGridHeight * .7;
dataArea.height(newDataAreaHeight);
gridElement.height(newGridHeight);
gridElement.data("kendoGrid").refresh();
}
var resizeListener = function () {
$(window).one("resize", function () {
resizeGrid();
setTimeout(resizeListener, 500);
});
};
Here is the html:
<div class="col-md-2">
<div class="panel panel-default">
<div class="panel-heading">Line of Business</div>
<div class="panel-body" id="lobnav"></div>
</div>
<div class="panel panel-default">
<div class="panel-heading">Application</div>
<div class="panel-body" id="lobapp"></div>
</div>
<div class="panel panel-default">
<div class="panel-heading">Filter</div>
<div class="panel-body" id="jobfilter">
</div>
</div>
</div>
<div class="col-md-10">
<div id="boxesgrid"></div>
</div>
Here is the rest of the javascript/kendo code:
$(document).ready(function () {
resizeListener();
var isParent, appId, lobId, boxId;
var apiUrl = '#ViewBag.ApiUrl';
var lobDataSource = new kendo.data.DataSource({
transport: {
read: {
url: apiUrl + "Lob"
}
},
schema: {
model: {
id: "LobId",
hasChildren: "HasChildren"
}
}
});
var appsDataSource = new kendo.data.DataSource({
transport: {
read: {
url: apiUrl + "App"
},
parameterMap: function (data, action) {
if (action === "read") {
data.lobid = lobId;
data.parent = isParent;
return data;
} else {
return data;
}
}
}
});
var filterDataSource = new kendo.data.DataSource({
transport: {
read: {
url: apiUrl + "Theme"
}
},
schema: {
model: { id: "FilterId" }
}
});
var boxesDataSource = new kendo.data.DataSource({
transport: {
read: {
url: apiUrl + "Process"
},
parameterMap: function (data) {
data.appid = appId;
data.parent = isParent;
data.lobid = lobId;
return kendo.stringify(data);
}
},
schema: {
data: "Data",
total: "Total",
model: { id: "JobId" }
},
serverPaging: true,
serverFiltering: true,
serverSorting: true
});
var lobnav = $("#lobnav").kendoTreeView({
select: function (e) {
var tree = this;
var src = tree.dataItem(e.node);
lobId = src.LobId;
isParent = src.HasChildren;
},
change: function (e) {
appsDataSource.read();
},
dataSource: {
transport: {
read: {
url: apiUrl + "Lob"
}
},
schema: {
model: {
id: "LobId",
hasChildren: "HasChildren"
}
}
},
loadOnDemand: false,
dataTextField: "LobName"
});
var appnav = $("#lobapp").kendoListView({
selectable: "single",
autoBind: false,
change: function () {
var idx = this.select().index();
var itm = this.dataSource.view()[idx];
appId = itm.AppId;
boxesDataSource.query({
page: 1,
pageSize: 35
});
},
template: "<div class='pointercursor'>${AppName}</div>",
dataSource: appsDataSource
});
var jobsfilter = $("#jobfilter").kendoListView({
selectable: "single",
loadOnDemand: false,
template: "<div class='pointercursor' id=${FilterId}>${FilterName}</div>",
dataSource: filterDataSource,
dataBound: function () {
var dsource = $("#jobfilter").data("kendoListView").dataSource;
if (dsource.at(0).FilterName !== "All") {
dsource.insert(0, { FilterId: 0, FilterName: "All" });
}
},
change: function () {
var itm = this.select().index(), dataItem = this.dataSource.view()[itm];
var appDs = appsDataSource.view(), apps = $("#lobapp").data("kendoListView"),
selected = $.map(apps.select(), function (item) {
return appDs[$(item).index()].AppName;
});
if (selected.length > 0) {
if (dataItem.FilterId !== 0) {
var $filter = new Array();
$filter.push({ field: "JobStatusId", operator: "eq", value: dataItem.FilterId });
jgrid.dataSource.filter($filter);
} else {
jgrid.dataSource.filter({});
}
}
}
});
var jgrid = $("#boxesgrid").kendoGrid({
columns: [
{
field: "AppName",
title: "App"
},
{
field: "JobId",
title: "Job Id"
},
{
field: "JobName",
title: "Job Name",
},
{
field: "JobStatus",
title: "Status"
},
{
field: "JobStatusId",
title: "Status Code"
},
{
field: "HasChildren",
title: "Has Children"
},
{
field: "ChildrenCount",
title: "Child Jobs"
}
],
sortable: {
mode: "single",
allowUnsort: true
},
pageable: {
pageSizes: [35],
numeric: true,
refresh: true,
pageSize: 35
},
autoBind: false,
scrollable: true,
resizable: true,
detailInit: detailInit,
dataSource: boxesDataSource
}).data("kendoGrid");
function detailInit(e) {
var eventData = e;
$.ajax({
url: apiUrl + "ProcessJobs",
type: "POST",
data: {BoxId: e.data.JobId, AppId: e.data.AppId},
dataType: "json",
success: function(data, status, xhr) {
initializeDetailGrid(eventData, data);
}
});
};
function initializeDetailGrid(e, result) {
var moreChildren = result[0].HasChildren;
var gridBaseOptions = {
dataSource: result,
scrollable: false,
sortable: true,
columns: [
{
field: "ParentJobId",
title: "Parent Job"
},
{
field: "JobId",
title: "Job Id"
},
{
field: "JobName",
title: "Job Name",
},
{
field: "JobStatus",
title: "Status"
},
{
field: "JobStatusId",
title: "Status Code"
},
{
field: "HasChildren",
title: "Has Children"
},
{
field: "ChildrenCount",
title: "Child Jobs"
}
]
};
var gridOptions = {};
if (moreChildren) {
gridOptions = $.extend({}, gridBaseOptions, { detailInit: detailInit });
} else {
gridOptions = gridBaseOptions;
};
$("<div/>").appendTo(e.detailCell).kendoGrid(gridOptions);
};
});
The resize function needed to be changed. The error was calling refresh on the grid, rather than resize. The corrected function looks like:
function resizeGrid() {
var gridElement = $("#boxesgrid");
var newGridHeight = $(window).height() > 800 ? 800 : $(document).height() * .75;
gridElement.height(newGridHeight);
gridElement.data("kendoGrid").resize();
}
Setting the data area separately was incorrect, as well.
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);