Kendo ui grid - Change row template content dynamically - kendo-ui

I came across this, and i really don´t know how to change it. I have column field like this:
{ field: "nome", title: "Nome", width: "20px", template: '<span><img id=idIconRowFolder src="icon_rowFolder.png" style="float: left;width: 20%;height: 16px;width: 16px;margin-top: 2%;"/></span>#= nome #',hideMe: true},
As you can see, i´m using a template and inside it there´s an image...it´s basically a icon that appears on the left side of the text in each row. What i want is to change this icon dinamically, so i know i have to use the dataBound function, and iterate through rows, and i´m actually doing this, but i don´t know how to access the template and his content:
my dataBound:
var grid = this;
grid.tbody.find('>tr').each(function()
{
var dataItem = grid.dataItem(this);
console.log(dataItem);
if(dataItem.tipo === 'pdf')
{
"what do i do here" ?
}
});
Thanks for your time, regards.
EDIT:
Hi everyone, thanks to your suggestions, i found a way, here it is for someone who could have the same problem:(in the databound put this)
var grid = $("#gridBaseDados").data("kendoGrid");
$(grid.tbody).find('tr').each(function ()
{
var dataItem = grid.dataItem(this).tipo;
var ficheiroValExtension = dataItem.split('.').pop();
if(ficheiroValExtension === 'pdf')
{
$(this).find('img').prop('src', 'index.hyperesources/icon_rowPdf.png').css('width','17px').css('height','22px');
}
}

Please try with the below code snippet.
<!DOCTYPE html>
<html>
<head>
<title>Jayesh Goyani</title>
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2015.3.1111/styles/kendo.common.min.css">
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2015.3.1111/styles/kendo.rtl.min.css">
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2015.3.1111/styles/kendo.default.min.css">
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2015.3.1111/styles/kendo.mobile.all.min.css">
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://kendo.cdn.telerik.com/2015.3.1111/js/angular.min.js"></script>
<script src="http://kendo.cdn.telerik.com/2015.3.1111/js/jszip.min.js"></script>
<script src="http://kendo.cdn.telerik.com/2015.3.1111/js/kendo.all.min.js"></script>
</head>
<body>
<div id="Grid">
</div>
<script>
$(document).ready(function () {
$("#Grid").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "http://demos.kendoui.com/service/Northwind.svc/Orders",
dataType: "jsonp"
},
schema: {
model: {
fields: {
OrderID: { type: "number" },
Freight: { type: "number" },
ShipName: { type: "string" },
OrderDate: { type: "date" },
ShipCity: { type: "string" }
}
}
},
pageSize: 10,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
dataBound: onDataBound,
filterable: true,
sortable: true,
pageable: true,
columns: [{
field: "OrderID",
filterable: false
},
"Freight",
{
field: "OrderDate",
title: "Order Date",
width: 120,
format: "{0:MM/dd/yyyy}"
}, {
field: "ShipName",
title: "Ship Name",
width: 260
}, {
field: "ShipCity",
title: "Ship City",
template: '<img id=idIconRowFolder src="icon_rowFolder.png" style="float: left;width: 20%;height: 16px;width: 16px;margin-top: 2%;"/>'
}
]
});
});
function onDataBound(e) {
var grid = $("#Grid").data("kendoGrid");
$(grid.tbody).find('tr').each(function () {
$(this).find('img').prop('src', 'Your new image src');
//Below syntax will return orderID
//$($(this).find('td').get(0)).html()
});
}
</script>
</body>
</html>
Let me know if any concern.

As i understand you want to show specific image corresponding to each data item. Then you have two options:
1.Additional field in dataSource that represents img.src
{
field: "nome",
title: "Nome",
width: "20px",
template: '<span><img src="#=imgSrc#" .../></span>#= nome #',
hideMe: true
}
2.Use clientSide function that return image source dependent on data item:
{
field: "nome",
title: "Nome",
width: "20px",
template: '<span><img src="#=getImgSrc(data)#" .../></span>#= nome #',
hideMe: true
}
and function itself:
var getImgSrc = function(item)
{
if(item.tipo === 'pdf') { return ... }
...
}
Update: of course for that no need to iterate dataSource in dataBound event

Related

Kendo template auto increasement

Hello I would like to know how I can use a for loop in a template to add on a number 1 onward
as this is what I would get in the picture below
the rest are being call by the backend but however this S/N is just a number incensement from 1 onward
enter image description here
// Call the table to the kendogrid where we use our datasource
$("#customer-list").kendoGrid({
dataSource: dataSource,
height: $(window).height()-$("#customer-list").position()["top"]-180,
selectable: "single, row",
change: function(e) {
console.log("change", this.dataItem(this.select()[0]));
},
scrollable: {
endless: true,
},
columns: [{
field: "",
title: "S/N",
headerAttributes: { "class": "k-text-center" },
width: 60,
template: `1`
}, {
field: "",
title: "Profile",
headerAttributes: { "class": "k-text-center" },
width: 150,
template:`
<img class="imageinside" src='#=data.Picture#' width="100px" height="100px" onError="this.onerror=null;this.src='../../assets/images/avatar.png';" style="border-radius:50px"/>
`
}, {
field: "",
title: "Customer Name",
template:`
<div id="customernameid">#=data.Name#</div>
`
}],
});
There's a solution for this in the knowledge base here, using the page() and pageSize() methods of the Data Source, as well as a counter variable.
See the code snippet for the proposed solution.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Kendo UI Snippet</title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2022.1.412/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/2022.1.412/js/kendo.all.min.js"></script>
</head>
<body>
<div id="grid"></div>
<script>
var record = 0;
$("#grid").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "//demos.telerik.com/kendo-ui/service/Northwind.svc/Customers"
},
pageSize: 20
},
sortable: true,
columns: [
{
title: "#",
template: "#= ++record #",
width: 50
}, {
field: "ContactName", title: "Contact Name"
}, {
field: "CompanyName",
title: "Company Name"
}, {
field: "Country",
width: 150
}
],
pageable: true,
dataBinding: function() {
record = (this.dataSource.page() -1) * this.dataSource.pageSize();
}
});
</script>
</body>
</html>

How to restrict the check box check to 5 in Kendo UI grid

How to restrict the check box check to 5 in Kendo UI grid.
I am using Kendo UI grid with check box. I want to restrict check box selection to 5
Please find the code attached
$(function () {
$("#grid").kendoGrid({
dataSource: {
pageSize: 10,
transport: {
read: {
url: "url",
dataType: "json"
}
},
schema: {
model: {
id: "Id",
fields: {
Id: {
type: "string"
},
Title: {
type: "string"
},
OrderDate: {
type: "date",
defaultValue: null
}
}
}
}
},
pageable: true,
persistSelection: true,
change: onChange,
columns: [
{ selectable: true, width: "50px" },
{ field: "Title", title: "Title" },
{ field: "OrderDate", title: "Order Date", format: "{0:MM/dd/yyyy}", encoded: true }
]
});
});
function onChange(arg) {
//console.log("The selected product ids are: [" + this.selectedKeyNames().join(", ") + "]");
}
Thanks in advance
This is tested code according your requirement only difference is that checkbox column created with template.
Reference link : https://docs.telerik.com/kendo-ui/controls/data-management/grid/how-to/Selection/grid-selection-checkbox
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Kendo UI Snippet</title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.1.115/styles/kendo.common.min.css"/>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.1.115/styles/kendo.rtl.min.css"/>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.1.115/styles/kendo.silver.min.css"/>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.1.115/styles/kendo.mobile.all.min.css"/>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2019.1.115/js/kendo.all.min.js"></script>
</head>
<body>
<div id="grid"></div>
<button id="showSelection">Show selected IDs</button>
<script>
$(document).ready(function () {
//DataSource definition
var crudServiceBaseUrl = "https://demos.telerik.com/kendo-ui/service",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/Products",
dataType: "jsonp"
},
update: {
url: crudServiceBaseUrl + "/Products/Update",
dataType: "jsonp"
},
destroy: {
url: crudServiceBaseUrl + "/Products/Destroy",
dataType: "jsonp"
},
create: {
url: crudServiceBaseUrl + "/Products/Create",
dataType: "jsonp"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return {
models: kendo.stringify(options.models)
};
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "ProductID",
fields: {
ProductID: {
editable: false,
nullable: true
},
ProductName: {
validation: {
required: true
}
},
UnitPrice: {
type: "number",
validation: {
required: true,
min: 1
}
},
Discontinued: {
type: "boolean"
},
UnitsInStock: {
type: "number",
validation: {
min: 0,
required: true
}
}
}
}
}
});
//Grid definition
var grid = $("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
height: 430,
//define dataBound event handler
dataBound: onDataBound,
toolbar: ["create"],
columns: [
//define template column with checkbox and attach click event handler
{ template: "<input type='checkbox' class='checkbox' />" },
"ProductName", {
field: "UnitPrice",
title: "Unit Price",
format: "{0:c}",
width: "100px"
}, {
field: "UnitsInStock",
title: "Units In Stock",
width: "100px"
}, {
field: "Discontinued",
width: "100px"
}, {
command: ["edit", "destroy"],
title: " ",
width: "172px"
}
],
editable: "inline"
}).data("kendoGrid");
//bind click event to the checkbox
grid.table.on("click", ".checkbox" , selectRow);
$("#showSelection").bind("click", function () {
var checked = [];
for(var i in checkedIds){
if(checkedIds[i]){
checked.push(i);
}
}
alert(checked);
});
});
var checkedIds = {};
//on click of the checkbox:
function selectRow() {
//// *********Prevent to select more than 5 record*************************
if(Object.keys(checkedIds).length>=5)
{
this.checked=false;
}
/// **********************************
var checked = this.checked,
row = $(this).closest("tr"),
grid = $("#grid").data("kendoGrid"),
dataItem = grid.dataItem(row);
checkedIds[dataItem.id] = checked;
if (checked) {
//-select the row
row.addClass("k-state-selected");
} else {
//-remove selection
row.removeClass("k-state-selected");
}
}
//on dataBound event restore previous selected rows:
function onDataBound(e) {
var view = this.dataSource.view();
for(var i = 0; i < view.length;i++){
if(checkedIds[view[i].id]){
this.tbody.find("tr[data-uid='" + view[i].uid + "']")
.addClass("k-state-selected")
.find(".checkbox")
.attr("checked","checked");
}
}
}
</script>
</body>
</html>
Let me know if you have questions or concerns.

How to override editing row and call custom edit in jsgrid

Tried this How to customize edit event in JsGrid as below. But doesnt seem to work
$("#jsgrd").jsGrid({
data: ds,
fields: [{
type: "control",
editItem: editrow(item)
}, ]
});
function editrow(item) {
var $row = this.rowByItem(item);
if ($row.length) {
console.log('$row: ' + JSON.stringify($row)); // I modify this
this._editRow($row);
}
}
The error I get now is "item" not defined.
What I m looking for is, when user clicks edit, I want to get the rowid stored in a hidden col and use it to fetch more data from server and populate outside jsgrid. And avoid changing the row to edit mode
You are not using the documented way. You should use editTemplate.
A simple working example is:
$(document).ready(function() {
$("#grid").jsGrid({
width: "100%",
editing: true,
autoload: true,
data: [ { id:1, name:"Tom"}, {id:2, name:"Dick"}],
fields: [
{ name: "id", type: "text", title: "Id"},
{ name: "name", type: "text", title: "Name",
editTemplate: function(item) {
return "<input type='checkbox'>" + item;
}},
{ type: "control"}
]
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid-theme.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.js"></script>
<div id="grid">
Test
</div>
For the purpose of illustration, I turn the edit of the name field from the standard text box into a check box.
You could use itemTemplate to get the required result.
itemTemplate is a function to create cell content. It should return markup as string, DomNode or jQueryElement. The function signature is function(value, item), where value is a value of column property of data item, and item is a row data item.
Inside of itemTemplate you can customise your dom element based on your requirement.
Run Demo
$("#jsGrid").jsGrid({
width: "100%",
height: "auto",
paging: false,
//for loadData method Need to set auto load true
autoload: true,
noDataContent: "Directory is empty",
controller: {
loadData: function(filter) {
var data = [{
id: 1,
nickname: "Test",
email: "t#gmail.com"
}, {
id: 2,
nickname: "Test 1",
email: "t1#gmail.com"
}, {
id: 3,
nickname: "Test 2",
email: "t2#gmail.com"
}, {
id: 4,
nickname: "Test 3",
email: "t3#gmail.com"
}];
return data;
}
},
fields: [{
name: "nickname",
type: "text",
width: 80,
title: "Name"
}, {
name: "email",
type: "text",
width: 100,
title: "Email Address",
readOnly: false
}, {
type: "control",
itemTemplate: function(value, item) {
var editDeleteBtn = $('<input class="jsgrid-button jsgrid-edit-button" type="button" title="Edit"><input class="jsgrid-button jsgrid-delete-button" type="button" title="Delete">')
.on('click', function (e) {
console.clear();
if (e.target.title == 'Edit') {
//Based on button click you can make your customization
console.log(item); //You can access all data based on item clicked
e.stopPropagation();
} else {
//Based on button click you can make your customization
console.log('Delete')
}
});
return editDeleteBtn; //
},
}]
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid-theme.min.css" />
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.js"></script>
<div id="jsGrid"></div>

Custom filter with dropdown to grid

here is the HTML page which i am working with,it's not working properly.
where is the issue can any one check it once.
here issue after the filter the grid the drop down value also changing or filtering.
can Any one check this code in html page.
<!DOCTYPE html>
<html lang="en-US">
<head>
<link href="http://cdn.kendostatic.com/2013.1.319/styles/kendo.common.min.css" rel="stylesheet" type="text/css" />
<link href="http://cdn.kendostatic.com/2013.1.319/styles/kendo.dataviz.min.css" rel="stylesheet" type="text/css" />
<link href="http://cdn.kendostatic.com/2013.1.319/styles/kendo.default.min.css" rel="stylesheet" type="text/css" />
<link href="http://cdn.kendostatic.com/2013.1.319/styles/kendo.dataviz.default.min.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://cdn.kendostatic.com/2013.1.319/js/kendo.all.min.js"></script>
<script src="http://cdn.kendostatic.com/2013.1.319/js/kendo.aspnetmvc.min.js"></script>
</head>
<body>
<div id="example" class="k-content">
<span class="nwcselection">data</span>
<input id="ddl"/></div>
<input type="button" id="btnfilter" value="Filter" onclick="Filter()" />
<div id="grid"></div>
</div>
<script type="text/javascript">
var data =new kendo.data.DataSource({
type: "odata",
transport: {
read:
"http://demos.kendoui.com/service/Northwind.svc/Products",
},
});
function createGrid()
{
var grid= $("#grid").kendoGrid({
dataSource:data,
schema: {
model: {
fields: {
ProductID: { type: "number" },
UnitPrice: { type: "number" },
ProductName: { type: "string" },
} }},
pageable: true,
columns: [
{ field: "ProductID", title:"Product ID", width:100 },
{ field: "ProductName", title:"Product Name" },
{ field: "UnitPrice", title:"Unit Price", width: 100 } ]
});
}
function dd()
{
$("#ddl").kendoDropDownList({
dataSource: data,
optionLabel: "Select category...",
dataTextField: "ProductName",
dataValueField: "ProductName"
}).data("kendoDropDownList");
}
function Filter() {
$("#btnfilter").click(function () {
$filter = new Array();
$ProductName = $("#ddl").data("kendoDropDownList").value();
if($ProductName)
{
$filter.push({ field: "ProductName",
operator: "contains", value: $ProductName });
}
var grid = $("#grid").data("kendoGrid");
grid.dataSource.filter({
logic: "and",
filters: $filter
});
});
}
$(document).ready(function () {
createGrid();
Filter();
dd();
});
</script>
</body>
The problem is that you use the same DataSource for the Grid and the DropDown: they are like pointers to the same object. Filtering one will filter the other because they are actually the same thing.
Try creating the DataSource twice:
var ds1 =new kendo.data.DataSource({
type: "odata",
transport: {
read:
"http://demos.kendoui.com/service/Northwind.svc/Products"
}
});
var ds2 =new kendo.data.DataSource({
type: "odata",
transport: {
read:
"http://demos.kendoui.com/service/Northwind.svc/Products"
}
});
and then use each of them in a different element:
var grid = $("#grid").kendoGrid({
dataSource: ds1,
schema : {
model: {
fields: {
ProductID : { type: "number" },
UnitPrice : { type: "number" },
ProductName: { type: "string" }
} }},
pageable: true,
columns : [
{ field: "ProductID", title: "Product ID", width: 100 },
{ field: "ProductName", title: "Product Name" },
{ field: "UnitPrice", title: "Unit Price", width: 100 }
]
});
$("#ddl").kendoDropDownList({
dataSource : ds2,
optionLabel : "Select category...",
dataTextField : "ProductName",
dataValueField: "ProductName"
}).data("kendoDropDownList");

kendo ui grid filter autocomplete

i have this code:
$("#grid_detail").kendoGrid({
dataSource: {
data: orders
},
filterable: {
extra: false,
operators: {
string: {
contains: "Contains",
}
}
},
sortable: true,
columns: [
{
field: "Buyer",
title: "buyer",
width: "40"
},
{
field: "name",
title: "Article name",
width: "40"
},
{
field: "paid",
title: "Paid",
width: "20",
filterable: false
}
]
});
now, how can i filter on field buyer, but to use autocomplete, and to show all buyers that are in dataSource ?
I tried with this, on buyer filed, but still nothing.
filterable: function(element){
element.kendoAutoComplete({
dataSource: orders,
dataTextField: "buyer",
})
}
Thanks.
First, in the columns you say that the column name is Buyer but in that autocomplete you use buyer.
Said that, what you should do is generating the autocomplete in filterable.ui. So the column definition for buyer is:
{
field : "buyer",
title : "Buyer",
width : "40",
filterable: {
ui: function (element) {
element.kendoAutoComplete({
dataSource : orders,
dataTextField: "buyer"
})
}
}
},
First we specify a single filter criterion using the filterable->extra=false setting, and limit the filter operators for string columns to starts with, equal and not equal only. Then we define built-in date picker UI to filter the datetime column in the grid, and instantiate Kendo UI AutoComplete and DropDownList for the Title and City columns, respectively.
To create the dropdown filters, we assign javascript functions to the filterable->ui attributes of the corresponding columns.
<!DOCTYPE html>
<html>
<head>
<base href="https://demos.telerik.com/kendo-ui/grid/filter-menu-customization">
<style>html { font-size: 14px; font-family: Arial, Helvetica, sans-serif; }</style>
<title></title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.1023/styles/kendo.default-v2.min.css" />
<script src="https://kendo.cdn.telerik.com/2019.3.1023/js/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2019.3.1023/js/kendo.all.min.js"></script>
</head>
<body>
<script src="../content/shared/js/people.js"></script>
<div id="example">
<div id="grid"></div>
<script>
$(document).ready(function() {
$("#grid").kendoGrid({
dataSource: {
data: createRandomData(50),
schema: {
model: {
fields: {
City: { type: "string" },
Title: { type: "string" },
BirthDate: { type: "date" }
}
}
},
pageSize: 15
},
height: 550,
scrollable: true,
filterable: {
extra: false,
operators: {
string: {
startswith: "Starts with",
eq: "Is equal to",
neq: "Is not equal to"
}
}
},
pageable: true,
columns: [
{
title: "Name",
width: 160,
filterable: false,
template: "#=FirstName# #=LastName#"
},
{
field: "City",
width: 130,
filterable: {
ui: cityFilter
}
},
{
field: "Title",
filterable: {
ui: titleFilter
}
},
{
field: "BirthDate",
title: "Birth Date",
format: "{0:MM/dd/yyyy HH:mm tt}",
filterable: {
ui: "datetimepicker"
}
}
]
});
});
function titleFilter(element) {
element.kendoAutoComplete({
dataSource: titles
});
}
function cityFilter(element) {
element.kendoDropDownList({
dataSource: cities,
optionLabel: "--Select Value--"
});
}
</script>
</div>
</body>
</html>

Resources