CodePen javascript code does not work in local - javascript

First of all I'm new to javascript
I would like to reuse the code in this codepen
$('a[href*=#]').click(function(){
return false;
});
var animationEndEvent = "webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend";
var Person = {
wrap: $('#people'),
people: [
{
name: 'Linda',
age: 25,
img: "https://i.imgur.com/QZuGC10.jpg"
},
{
name: 'Lisa',
age: 20,
img: "https://i.imgur.com/1EWwp59.jpg"
},
{
name: 'Sandra',
age: 18,
img: "https://i.imgur.com/Lu3laIj.jpg"
},
{
name: 'Chloe',
age: 18,
img: "https://i.imgur.com/WgYIxhw.png"
},
{
name: 'Alexa',
age: 23,
img: "https://i.imgur.com/D0PQegY.png"
},
{
name: 'Maria',
age: 21,
img: "https://i.imgur.com/eqd5IhH.jpg"
},
{
name: 'Emma',
age: 24,
img: "https://i.imgur.com/4F9NXPo.png"
},
{
name: 'Sara',
age: 18,
img: "http://i40.tinypic.com/ofxe21.jpg"
},
{
name: 'Lara',
age: 22,
img: "https://i.imgur.com/HMkdN6A.jpg"
}
],
add: function(){
var random = this.people[Math.floor(Math.random() * this.people.length)];
this.wrap.append("<div class='person'><img alt='" + random.name + "' src='" + random.img + "' /><span><strong>" + random.name + "</strong>, " + random.age + "</span></div>");
}
}
var App = {
yesButton: $('.button.yes .trigger'),
noButton: $('.button.no .trigger'),
blocked: false,
like: function(liked){
var animate = liked ? 'animateYes' : 'animateNo';
var self = this;
Person.add();
if (!this.blocked) {
this.blocked = true;
$('.person').eq(0).addClass(animate).one(animationEndEvent, function() {
$(this).remove();
self.blocked = false;
});
}
}
};
var Phone = {
wrap: $('#phone'),
clock: $('.clock'),
updateClock: function() {
var date = new Date();
var hours = date.getHours();
var min = date.getMinutes();
hours = (hours < 10 ? "0" : "") + hours;
min = (min < 10 ? "0" : "") + min;
var str = hours + ":" + min;
this.clock.text(str);
}
}
App.yesButton.on('mousedown', function() {
App.like(true);
});
App.noButton.on('mousedown', function() {
App.like(false);
});
$(document).ready(function() {
Person.people.forEach(function(person){
new Image().src = person.img;
});
Phone.updateClock();
setInterval('Phone.updateClock()', 1000);
Person.add();
Person.add();
Person.add();
Person.add();
});
(https://codepen.io/renatorib/pen/extCA).
But I can't make it work in local.
I have inserted jquery ( the same version he uses //cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js)
And I have converted sass to css.
It look the same, but its javascript part doesn't work ( no photos no buttons nothing..) No console errors...
I don't know what else to do..
PD: Sorry for my English, I hope I explained myself

Replace this and use this jQuery version on bottom.
$('a[href*="#!..."]').click(function(){
return false;
});
Full Repo

If you follow these steps it should work.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>your title</title>
<!-- step 1 add css file-->
<link href="your-style.css" rel="stylesheet" type="text/css">
<!-- step 2 add jquery library-->
<script src="jquery.js"></script>
<!--step 3 add script that run after dom ready-->
<script>
$(function() {
// dom is ready
// your script goes here
});
</script>
</head>
<body>
<!-- step 4 html structur goes hear. Note that the selectors that you select in script must be the same in html-->
</body>
</html>

Related

Copying data from a kendo treelist with keeping the table structure

I have an editable multi selectable kendo Treelist. I would like to be able to select part of the grid and copy paste its data in the same grid (other columns and rows) or to a text file. It is important to paste it with the same structure in the new table.
The copy feature is not supported for kendo Treelist.
Is there a way to do that with use of JavaScript and jQuery?
Kendo demo
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Kendo UI Snippet</title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2023.1.117/styles/kendo.default-v2.min.css"/>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2023.1.117/js/kendo.all.min.js"></script>
</head>
<body>
<div id="treeList"></div>
<script>
$("#treeList").kendoTreeList({
columns: [
{ field: "name" },
{ field: "age" }
],
selectable: "multiple, cell",
editable:"incell",
dataSource: [
{ id: 1, parentId: null, name: "Jane Doe", age: 22 },
{ id: 2, parentId: 1, name: "John Doe", age: 24 },
{ id: 3, parentId: 1, name: "Jenny Doe", age: 3 }
]
});
</script>
</body>
</html>
I have used two buttons, one for copying and one for pasting. The events functions are as below. This solved my problem and I can also paste the copied text in excel.
<button onClick="copying()" >Copy</button>
<button onClick="pasting()" >Paste</button>
<div id="treeList"></div>
<script>
$("#treeList").kendoTreeList({
columns: [
{ field: "name" },
{ field: "age" }
],
selectable: "multiple, cell",
editable:"incell",
dataSource: [
{ id: 1, parentId: null, name: "Jane Doe", age: 22 },
{ id: 2, parentId: 1, name: "John Doe", age: 24 },
{ id: 3, parentId: 1, name: "Jenny Doe", age: 3 }
]
});
</script>
var copiedText="";
function copying(){
if(copiedText !== ""){
return;
}
var grid = $("#treeList").data("kendoTreeList");
var selected = grid.select();
var previousRowID = selected.eq(0).parent().index();
var isNewLine = true;
selected.each(function() {
var row = $(this).closest("tr");
var dataItem = grid.dataItem(this);
if (previousRowID !== $(this).parent().index()) {
copiedText += "\r\n";
isNewLine = true;
}
previousRowID = $(this).parent().index();
var colIndx = $("td", row).index(this);
var column = grid.columns[colIndx];
var data = dataItem;
var value = dataItem[column.field];
if (!isNewLine) {
copiedText += "\t";
}
copiedText += value;
isNewLine = false;
});
var textarea = $("<textarea>");
var offset = $(this).offset();
// Position the textarea on top of the Treelist and make it transparent.
textarea.css({
position: 'absolute',
opacity:0,
border: 'none',
width: $(this).find("table").width(),
height: $(this).find(".k-grid-content").height()
});
textarea.val(copiedText)
.appendTo('body')
.focus()
.select();
document.execCommand('copy');
setTimeout(function(){
textarea.remove();
});
}
function pasting() {
var pasteVal = copiedText;
var grid = $("#treeList").data("kendoTreeList");
if (pasteVal) {
var selectedArr= Object.values($(".k-grid td.k-selected"));
var pasteArray = pasteVal.split("\r\n").filter(r => r !== "").map(r => r.split("\t"));
pasteArray.forEach(function( item, index) {
selectedArr[index].innerHTML = item;
});
grid.refresh();
}
copiedText= "";
}

Kendo grid highlight all column by external value

I want to highlight the kendo grid cell by matching an external string text.
I googled a lot but found only searching a string in a particular column.
below is the code which works for one column
$("#grid").kendoGrid({
selectable: "multiple cell",
allowCopy: true,
columns: [
{ field: "productName" },
{ field: "category" }
],
dataSource: [
{ productName: "Tea", category: "Beverages" },
{ productName: "Coffeete", category: "Beverageste" },
{ productName: "Ham", category: "Foodte" },
{ productName: "Bread", category: "Food" }
]
});
var grid = $("#grid").data('kendoGrid');
var value = 'te';
var regex = new RegExp(value, "gi");
var colIndex = 0;
grid.tbody.find('tr[data-uid]').each(function () {
var td = $(this).find('td:eq(' + colIndex + ')');
var item = grid.dataItem(this);
td.html(item.productName.replace(regex, '<span style="background-color:yellow">' + value + '</span>'));
});
But I want the search the string text across all columns.
Can anyone help me on this?
The best for doing that IMO is to use templates, e.g.:
template: "#= findText(data.fieldName) #"
The template will use a function to create the search highlight which can be something similiar as you already done:
var findText = function findText(text) {
let index = text.indexOf(value),
result = text;
// If substring is found in current text
if (index > -1) {
let regex = new RegExp(value, "gi");
result = result.replace(regex, '<span style="background-color:yellow">' + value + '</span>');
}
return result;
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled</title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.1023/styles/kendo.common.min.css">
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.1023/styles/kendo.rtl.min.css">
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.1023/styles/kendo.default.min.css">
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.1023/styles/kendo.mobile.all.min.css">
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2019.3.1023/js/angular.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2019.3.1023/js/jszip.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2019.3.1023/js/kendo.all.min.js"></script></head>
<body>
<div id="grid"></div>
<script>
var value = 'co';
var findText = function findText(text) {
let index = text.toLowerCase().indexOf(value),
result = text;
// If substring is found in current text
if (index > -1) {
let regex = new RegExp(`(${value})`, "gi");
result = result.replace(regex, '<span style="background-color:yellow">$1</span>');
}
return result;
};
$("#grid").kendoGrid({
selectable: "multiple cell",
allowCopy: true,
columns: [
{ field: "productName", template: "#= findText(data.productName) #" },
{ field: "category", template: "#= findText(data.category) #" }
],
dataSource: [
{ productName: "Tea", category: "Beverages" },
{ productName: "Coffeete", category: "Beverageste" },
{ productName: "Ham", category: "Foodte" },
{ productName: "Bread", category: "Food" }
]
});
</script>
</body>
</html>
Demo in Dojo

How to control an image in javascript

I want to preload my images and rotate them every 3 seconds.
I'm having trouble with the rotate and preload functions. I need to preload my images when the page first loads and rotate them every 3 seconds. I've tried having the images in an array and not in an array. Nothing seems to work.
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Index Page</title>
<link rel="stylesheet" type="text/css" href="css/main.css" />
<!-- JavaScript files -->
<script src="js/preloadImages.js" type="text/javascript"></script>
<script src="js/rotateImages.js" type="text/javascript"></script>
</head>
<body>
<div class "centered">
<img src="images/banner1.jpg" id="idBanner" alt="idBanner">
</div>
</body>
</html>
//JAVASCRIPT CODE//
window.onload=loadImage;
var images = [];
function loadImage(){
for (var i=0; i < arguments.length; i++){
images[i] = new Image();
images[i].src = preload.arguments[i];
}
}
preload(
"images/banner1.jpg", "images/banner2.jpg", "images/banner3.jpg", "images/silhouette.jpg", "images/work.jpg", "images/firefighter.jpg", "images/event.jpg")
window.onload=rotate;
var count=0;
var bannerImages = new Array("images/banner1.jpg", "images/banner2.jpg", "images/banner3.jpg");
function rotate(){
count++;
if (count==bannerImages.length){
count = 0;
}
document.getElementById("idBanner").src = bannerImages[count];
setTimeOut(rotate, 3*1000);
}
a way to go...
const ImgLoad = [ { img: null, src: 'images/banner1.jpg' }
, { img: null, src: 'images/banner2.jpg' }
, { img: null, src: 'images/banner3.jpg' }
, { img: null, src: 'images/silhouette.jpg' }
, { img: null, src: 'images/work.jpg' }
, { img: null, src: 'images/firefighter.jpg'}
, { img: null, src: 'images/event.jpg' }
]
, ImgBann = [ 'images/banner1.jpg', 'images/banner2.jpg', 'images/banner3.jpg' ]
, ImgRota = document.getElementById("idBanner")
var ItemBann = 0
for (let ref of ImgLoad)
{
ref.img = new Image()
ref.img.src = ref.src
}
setInterval(() =>
{
ItemBann = ++ItemBann % ImgBann.length
ImgRota.src = ImgBann[ItemBann]
}
, 3000)
you can also use: (to make sure all images are fully loaded before any "rotation")
const ImgLoad = [ { img: null, src: 'images/banner1.jpg' }
, { img: null, src: 'images/banner2.jpg' }
, { img: null, src: 'images/banner3.jpg' }
, { img: null, src: 'images/silhouette.jpg' }
, { img: null, src: 'images/work.jpg' }
, { img: null, src: 'images/firefighter.jpg'}
, { img: null, src: 'images/event.jpg' }
]
, ImgBann = [ 'images/banner1.jpg'
, 'images/banner2.jpg'
, 'images/banner3.jpg'
]
, ImgRota = document.getElementById("idBanner")
var ItemBann = 0
, ImgLoaded = 0
for (let ref of ImgLoad)
{
ref.img = new Image()
ref.img.onload = () =>{ ImgLoaded++ }
ref.img.src = ref.src
}
setInterval(() =>
{
if (ImgLoaded === ImgLoad.length )
{
ItemBann = ++ItemBann % ImgBann.length
ImgRota.src = ImgBann[ItemBann]
}
}
, 3000)

Free JQGrid - save-button in inlineNav not working when adding a second row

we've several Free JQGrids and a problem with adding new rows.
Click on the icon in inlineNav (ADD) a new row will be shown up, clicking the SAVE-Icon the first time works fine. But when adding a second row the Save-buttton in inlineNav will not work. Enter-key in the row works. After reload the whole grid, it will work only once again.
Following is the code of the grid
some defaults:
jQuery.extend($.jgrid.defaults,{
autowidth: true, pager:true, pgbuttons:false, pginput:false,
pgtext:false, datatype: "json", mtype: "POST",
rownumbers:true, rowNum:9999,
postData: {"savestate_encrypted" : function() {return $("input[name='savestate_encrypted']").val();}},
ondblClickRow: function (rowid, status, e) {
var $self = $(this), savedRow = $self.jqGrid("getGridParam", "savedRow");
if (savedRow.length > 0 && savedRow[0].id !== rowid) {
$self.jqGrid("restoreRow", savedRow[0].id);
}
$self.jqGrid("editRow", rowid, { focusField: e.target });
},
});
The grid itself:
jQuery("#grid").jqGrid({
url:"....",
jsonReader: {root: "resourceList"},
height: 500,
cmTemplate: { editable: true},
inlineEditing: {keys: true},
editurl: "....",
colModel:[ //Define Table Columns
{name: "name", label:"Name", key:true, hidden:false},
{name: "activeJobs", label:"aktive Jobs", width:250}
],
}).jqGrid("navGrid", {refresh:true, edit:false, del:true, search:false, add:false})
.jqGrid("inlineNav", {save:true, edit:true, add:true})
</script>
I've figured out that the line 15300 (sorry don't know how to find the branch version - 30.Jan 2017) in the grid source will set the "var ind" to false, when clicking on the button, pressing enter-key works perfect
var tmp = {}, tmp2 = {}, postData = {}, editable, k, fr, resp, cv, savedRow, ind = $self.jqGrid("getInd", rowid, true), $tr = $(ind),
opers = p.prmNames, errcap = getRes("errors.errcap"), bClose = getRes("edit.bClose"), isRemoteSave, isError,
displayErrorMessage = function (text, relativeElem)....
As a fast solution I wanted to subsribe on an event and reload the whole grid. But subscribe() seems to be gone (we are switching from the old struts-tag grid to javascript. I think bind is the correct way now, but which event?
ADDITION---------------------------
I've created a working code which will show a similiar problem without Ajax and Json. When clicking ADD, enter the values and then selecting SAVE in the inlineNav Bar everything is OK, but pressing ADD again, enter values and then select SAVE, the edit-mode will stay open. If you use the Enter-Key instead the SAVE-btn it will work.
<!DOCTYPE html>
<html lang="de"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="js/jquery-3.1.1.min.js"></script>
<script src="js/jquery-ui.min.js"></script>
<script src="js/jquery.jqgrid.src.js"></script>
<link rel="stylesheet" href="js/jquery-ui.min.css">
<link rel="stylesheet" href="js/ui.jqgrid.min.css">
</head>
<script type="text/javascript">
/* DEFAULTS */
jQuery.extend($.jgrid.defaults,{
autowidth: true, // nutzt die ganze verfügbare Breite
pager:true, // Fusszeile -
pgbuttons:false, // - ohne Seitenkontrollbuttons
pginput:false, // - ohne Eingabefeld
pgtext:false, // - ohne Text
rownumbers:true, // immer Zeilennummern
rowNum:9999, // bis zu 9999 Zeilen
ondblClickRow: function (rowid, status, e) {
var $self = $(this), savedRow = $self.jqGrid("getGridParam", "savedRow");
if (savedRow.length > 0 && savedRow[0].id !== rowid) {
$self.jqGrid("restoreRow", savedRow[0].id);
}
$self.jqGrid("editRow", rowid, { focusField: e.target });
},
});
// For JSON Response
/* jQuery.extend($.jgrid.inlineEdit,{
restoreAfterError:false,
errorfunc: function( response )
{
var resp = response;
alert("error7");
return false;
},
successfunc: function( response )
{
var resp = response;
var hasNoError = true;
// var hasNoError = (resp.responseJSON.actionErrors.length == 0);
return hasNoError;
}
});
*/
function dataset() {
"use strict";
var mydata2 = [
{ id: "10", name: "test" , value: "5"},
{ id: "20", name: "test20", value: "5"},
{ id: "30", name: "test30", value: "5"},
{ id: "40", name: "test40", value: "5"},
{ id: "50", name: "test50", value: "5"},
];
return mydata2;
};
</script>
<body>
<table id="grid"></table>
<script type="text/javascript">
jQuery("#grid").jqGrid({
data: dataset(),
colModel: [
{ name: "id", label:"ID"},
{ name: "name", label:"NAME", align: "center" },
{ name: "value", label:"VALUE", align: "center" }
],
cmTemplate: { editable: true, autoResizable: true },
}).jqGrid("navGrid", {refresh:true, edit:false, del:true, search:false, add:false})
.jqGrid("inlineNav", {save:true, edit:true, add:true})
</script>
</body></html>
If I correctly understand your problem then you want to reload the grid after saving. You can use jqGridInlineAfterSaveRow event for the purpose:
jQuery("#grid").on("jqGridInlineAfterSaveRow", function () {
setTimeout(function () {
jQuery("#grid").trigger("reloadGrid");
}, 0);
});

TypeError: grid is undefined

I have uploaded a page where the error occurs. It´s displayed in the console (please use F12 in Firefox or Chrome Browser).
http://preventdefault.lima-city.de/index.php
This line is wrong: "kendo.stringify(grid.getOptions())"
My Question: How must i change this code so that i could store the changed table settings?
I also insert the html code here, Thx for answer !
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1411/styles/kendo.common.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1411/styles/kendo.rtl.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1411/styles/kendo.default.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1411/styles/kendo.dataviz.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1411/styles/kendo.dataviz.default.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
<script src="http://cdn.kendostatic.com/2014.3.1411/js/jszip.min.js"></script>
<script src="http://cdn.kendostatic.com/2014.3.1411/js/kendo.all.min.js"></script>
<style type="text/css">
.button-center {
text-align: center; /* button position in grid */
}
</style>
</head>
<body role="document">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">WebSiteName</a>
</div>
<div>
<ul class="nav navbar-nav">
<li class="active">one</li>
<li>two</li>
</ul>
</div>
</div>
</nav>
<div class="container theme-showcase" id="main" role="main">
<div class="container">
<h1>Page<small> one</small></h1>
</div>
<div class="row-fluid">
<div id="grid_one"></div>
</div> <!-- row -->
<div class="row-fluid">
<div id="log"></div>
</div> <!-- row -->
</div> <!-- container -->
<script>
<!-- --------------------------------------------------------------------------------- -->
var firstNames = ["Nancy", "Andrew", "Janet", "Margaret", "Steven",
"Michael", "Robert", "Laura", "Anne", "Nige"],
lastNames = ["Davolio", "Fuller", "Leverling", "Peacock", "Buchanan",
"Suyama", "King", "Callahan", "Dodsworth", "White"],
cities = ["Seattle", "Tacoma", "Kirkland", "Redmond", "London",
"Philadelphia", "New York", "Seattle", "London", "Boston"],
titles = ["Accountant", "Vice President, Sales", "Sales Representative",
"Technical Support", "Sales Manager", "Web Designer",
"Software Developer", "Inside Sales Coordinator", "Chief Techical Officer",
"Chief Execute Officer"],
birthDates = [new Date("1948/12/08"), new Date("1952/02/19"), new Date("1963/08/30"),
new Date("1937/09/19"), new Date("1955/03/04"), new Date("1963/07/02"),
new Date("1960/05/29"), new Date("1958/01/09"), new Date("1966/01/27"),
new Date("1966/03/27")];
function createRandomData(count) {
var data = [], now = new Date();
for (var i = 0; i < count; i++) {
var firstName = firstNames[Math.floor(Math.random() * firstNames.length)],
lastName = lastNames[Math.floor(Math.random() * lastNames.length)],
city = cities[Math.floor(Math.random() * cities.length)],
title = titles[Math.floor(Math.random() * titles.length)],
birthDate = birthDates[Math.floor(Math.random() * birthDates.length)],
age = now.getFullYear() - birthDate.getFullYear();
data.push({
Id: i + 1,
FirstName: firstName,
LastName: lastName,
City: city,
Title: title,
BirthDate: birthDate,
Age: age
});
}
return data;
}
<!-- --------------------------------------------------------------------------------- -->
function onChangeSelection() {
var selectedItem = this.dataItem(this.select());
var Text = '<h1><small>row name=</small>' + selectedItem.FirstName + " " + selectedItem.LastName + "</h1>";
console.log(Text);
$("#log").html(Text);
$("#ordernumber").val(selectedItem.ordernumber);
}
<!-- --------------------------------------------------------------------------------- -->
function startbuttonclick(e) {
var data = this.dataItem($(e.currentTarget).closest("tr"));
var Text = "<h1><small>Button click name=</small> " + data.FirstName + " " + data.LastName + "</h1>";
console.log(Text);
$("#log").html(Text);
e.preventDefault();
}
<!-- --------------------------------------------------------------------------------- -->
$(document).ready(function() {
$("#grid_one").kendoGrid({
dataSource: {
data: createRandomData(10),
schema: {
model: {
fields: {
FirstName: { type: "string" },
LastName: { type: "string" },
City: { type: "string" },
Title: { type: "string" },
BirthDate: { type: "date" },
Age: { type: "number" }
}
}
},
pageSize: 10
},
height: 500,
dataBound: saveState,
columnResize: saveState,
columnShow: saveState,
columnHide: saveState,
columnReorder: saveState,
columnLock: saveState,
columnUnlock: saveState,
selectable: true,
resizable: true,
columnMenu: true,
scrollable: true,
sortable: true,
filterable: true,
change: onChangeSelection,
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5,
pageSizes: [5, 10, 20, 250]
},
columns: [
{
field: "FirstName",
title: "First Name",
width: "150px",
},
{
field: "LastName",
title: "Last Name",
width: "150px",
},
{
field: "City",
hidden: true
},
{
field: "Title",
hidden: true
},
{
field: "BirthDate",
title: "Birth Date",
template: '#= kendo.toString(BirthDate,"MM/dd/yyyy") #',
width: "175px",
},
{
field: "Age",
width: "150px",
},
{
command: {
text: "Start",
click: startbuttonclick },
title: "Start",
width: "65px",
attributes:{
"class":"button-center"}
}
]
});
<!-- ------------------------------------------------------------------------------ -->
var grid = $("#grid_one").data("kendoGrid");
function saveState(e) {
e.preventDefault();
localStorage["kendo-grid-one"] = kendo.stringify(grid.getOptions());
};
$(function (e) {
var options = localStorage["kendo-grid-one"];
if (options) {
grid.setOptions(JSON.parse(options));
} else {
grid.dataSource.read();
}
});
});
<!-- --------------------------------------------------------------------------------- -->
</script>
</body>
</html>
Edited for:
Your var grid = $("#grid_one").data("kendoGrid"); only defined once, and it may not have data upon defined, it maybe insert by your kendogrid after.
Domready Part should also need to have reference to it, you can either put it at origin location or move it into the function
From your and dfsq's replies, the problem is that json CANNOT store a function, so you have to add it back to when retrieved from the localstorage
In your current code, saveState will always be called before the setOptions one, which means the saveState just erased by your saveState function, so you have to move the setoptions code forward.
Changes a lot
$(document).ready(function() {
// Get options first
var options = localStorage["kendo-grid-one"];
if (options) {
options = JSON.parse(options);
// Workaround to addback event
options.columns[6].command.click = startbuttonclick;
}
$("#grid_one").kendoGrid({
dataSource: {
data: createRandomData(10),
schema: {
.....
});
if (options) {
$("#grid_one").data("kendoGrid").setOptions(options);
}
<!-- ------------------------------------------------------------------------------ -->
function saveState(e) {
var grid = $("#grid_one").data("kendoGrid");
e.preventDefault();
localStorage["kendo-grid-one"] = kendo.stringify(grid.getOptions());
};
See Demo Here, now it works.
saveState part use dfsq's may be better
options.columns[6].command.click = startbuttonclick; may be can write in a more elegant style, but here I just want to show why the issues come out and how to apply a basic solution.
I don't know kendo but the issue must be that the saveState function is called before the grid is declared.
JSFiddle: http://jsfiddle.net/8x7v7mga/1/
So somewhere in the construction of the kendo object, one of the saveState handlers is called.
You can avoid this by declaring the grid variable first and then in the saveState simply check if grid is defined or not:
var grid = null;
$("#grid_one").kendoGrid({ ... });
grid = $("#grid_one").data("kendoGrid");
function saveState(e) {
e.preventDefault();
grid && localStorage["kendo-grid-one"] = kendo.stringify(grid.getOptions());
};
The problem is that saveState function is called before grid is initialzed. you cantually don't need grid reference since saveState s called in grid context so you can simply use this instead:
function saveState(e) {
e.preventDefault();
localStorage["kendo-grid-one"] = kendo.stringify(this.getOptions());
};

Categories