Kendo Grid Automatically Fit Column Width except for Specific Column - javascript

I am looking for a way to let column(index = n) (by index number) or column(headingText = 'Address') (by column name) fill the gap on my kendo grid.
I know how to automatically fit column widths for a Kendo Grid:
<div id="example">
<div id="grid"></div>
<script>
$(document).ready(function() {
var grid = $("#grid").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Orders"
},
schema: {
model: {
fields: {
OrderID: {
type: "number"
},
ShipCountry: {
type: "string"
},
ShipCity: {
type: "string"
},
ShipName: {
type: "string"
},
OrderDate: {
type: "date"
},
ShippedDate: {
type: "date"
}
}
}
},
pageSize: 15
},
height: 550,
sortable: true,
resizable: true,
pageable: true,
dataBound: function() {
for (var i = 0; i < this.columns.length; i++) {
this.autoFitColumn(i);
}
},
columns: [{
field: "OrderDate",
title: "Order Date",
format: "{0:MM/dd/yyyy}"
},
{
field: "ShipCountry",
title: "Ship Country"
},
{
field: "ShipCity",
title: "Ship City"
},
{
field: "ShipName",
title: "Ship Name"
},
{
field: "ShippedDate",
title: "Shipped Date",
format: "{0:MM/dd/yyyy}"
},
{
field: "OrderID",
title: "ID"
}, {
field: "OrderDate",
title: "Order Date",
format: "{0:MM/dd/yyyy}"
},
{
field: "ShipCountry",
title: "Ship Country"
},
{
field: "ShipCity",
title: "Ship City"
},
{
field: "ShipName",
title: "Ship Name"
},
{
field: "ShippedDate",
title: "Shipped Date",
format: "{0:MM/dd/yyyy}"
},
{
field: "OrderID",
title: "ID"
}
]
});
});
</script>
</div>
<style>
#grid>table
{
table-layout: fixed;
}
</style>
I made a fiddle, but I don't know how to link in kendo grid:
https://jsfiddle.net/jp2code/p6cu5r29/2/
I could HARD CODE the column widths:
columns: [
{ field: "name", width: "200px" },
{ field: "tel", width: "10%" }, // this will set width in % , good for responsive site
{ field: "age" } // this will auto set the width of the content
],
But I'd like the grid to be more dynamic.
I can remove the empty space in a grid by leaving the autoFitColumn off of the last column:
<style>
.k-grid {
width: 700px;
}
</style>
<div id="grid1"></div>
<script>
function getMasterColumnsWidth(tbl) {
var result = 0;
tbl.children("colgroup").find("col").not(":last").each(function (idx, element) {
result += parseInt($(element).outerWidth() || 0, 10);
});
return result;
}
function adjustLastColumn() {
var grid = $("#grid1").data("kendoGrid");
var contentDiv = grid.wrapper.children(".k-grid-content");
var masterHeaderTable = grid.thead.parent();
var masterBodyTable = contentDiv.children("table");
var gridDivWidth = contentDiv.width() - kendo.support.scrollbar();
masterHeaderTable.width("");
masterBodyTable.width("");
var headerWidth = getMasterColumnsWidth(masterHeaderTable),
lastHeaderColElement = grid.thead.parent().find("col").last(),
lastDataColElement = grid.tbody.parent().children("colgroup").find("col").last(),
delta = parseInt(gridDivWidth, 10) - parseInt(headerWidth, 10);
if (delta > 0) {
delta = Math.abs(delta);
lastHeaderColElement.width(delta);
lastDataColElement.width(delta);
} else {
lastHeaderColElement.width(0);
lastDataColElement.width(0);
}
contentDiv.scrollLeft(contentDiv.scrollLeft() - 1);
contentDiv.scrollLeft(contentDiv.scrollLeft() + 1);
}
$("#grid1").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Employees"
},
pageSize: 6,
serverPaging: true,
serverSorting: true
},
height: 430,
pageable: true,
resizable: true,
columnResize: adjustLastColumn,
dataBound: adjustLastColumn,
columns: [{
field: "FirstName",
title: "First Name",
width: "100px"
}, {
field: "LastName",
title: "Last Name",
width: "150px"
}, {
field: "Country",
width: "100px"
}, {
field: "City",
width: "100px"
}, {
field: "Title",
width: "200px"
}, {
template: " "
}]
});
</script>
But, I don't want to always leave the last column super wide to fill the page.
I am looking for a more generic example showing how to let column(index = n) or column(headingText = 'Address') be the column that fills the gap.

I did it! Sharing with others:
function refreshGridColumns(grid, skipField) {
var index = -1;
console.log('refreshGridColumns: grid.columns.length = ' + grid.columns.length);
var columns = grid.options.columns;
// find address column and do not autofit it so that the grid fills the page
for (var i = 0; i < grid.columns.length; i++) {
if (0 < columns.length) {
console.log('refreshGridColumns: field = ' + columns[i].field);
if (columns[i].field == skipField) { // columns[i].title -- You can also use title property here but for this you have to assign title for all columns
index = i;
} else {
grid.autoFitColumn(i);
}
} else {
grid.autoFitColumn(i);
}
console.log('refreshGridColumns: i = ' + i);
}
console.log('refreshGridColumns: index = ' + index);
}
Kudos to Jayesh Goyani for this answer:
https://stackoverflow.com/a/34349747/153923

Related

How can I refresh "footer" on Kendo Ui Grid using JQuery

I Set Kendo Ui Grid and footer,
footer will get total price,
but it always can't get last data.
hope somebody can help to fix it.
and i try $("#Grid").data("kendoGrid").refresh();
but it didn't work for me.
kendoui grid set
dataSource
var AddGriddataSource = new kendo.data.DataSource({
data: [],
schema: {
model: {
fields: {
id: 'No',
Name: { editable: false, nullable: false },
txtStockNum: { editable: false, nullable: false },
txtReturnNum: { editable: true, nullable: false },
txtPricetax: { editable: false, nullable: false },
txtPriceNum1: { editable: false, nullable: false }
}
} // end of model
}, // end of schema
aggregate: [{ field: "txtPriceNum", aggregate: "sum" }, { field: "txtPriceNum1", aggregate: "sum" }],
});
Cell
var AddGridCells = [
{ field: "Name", title: "Name", width: "20px" },
{ field: "StockNum", title: "Stock", width: "20px" },
{ field: "txtReturnNum", title: "txtReturnNum", width: "100px", template: '<input id = "Del" class="returnDel" type="button" value="▼" style="margin: -1px" /><input id="Txt_test1" class="returnTxtBox" type="textbox" value= #=txtReturnNum# style="margin: 2px" /><input id = "plus" class="returnPlus" type="button" value="▲" style="margin: -1px" />' },
{ field: "txtPrice", title: "txtPrice", width: "20px", hidden: true },
{ field: "txtPricetax", title: "txtPricetax", width: "20px", format: "{0:n3}" },
{ field: "txtPriceNum", title: "Total", width: "20px", footerTemplate: "#= kendo.toString(sum, '0.000')#", hidden: true },
{ field: "txtPriceNum1", title: "Total", width: "30px", footerTemplate: "<span id='footerPlaceholder'>#= kendo.toString(sum, '0.000')#</span>", format: "{0:n3}" },
{ command: [{ text: "X", click: DelchooseDetails }], title: " ", width: "10px" },
];
and
$("#AddGrid").kendoGrid({
dataSource: AddGriddataSource,
selectable: "row",
scrollable: false,
columns: AddGridCells,
change: numberInput,
pageable: {
buttonCount: 3,
messages: GridPageMsg
},
height: '100%',
editable: true
}).data("kendoGrid");
JQuery todo
$(document).on('click', '.returnPlus', function (e) {
if (nowStatus != 0) {
return;
}
var ds2 = $("#AddGrid").data("kendoGrid").dataSource;
var row = $(this).closest("tr"),
grid = $("#AddGrid").data("kendoGrid"),
dataItem = grid.dataItem(row);
debugger;
ds2.fetch(function () {
dataItem.txtReturnNum = dataItem.txtReturnNum - (-1);
dataItem.txtPriceNum = dataItem.txtReturnNum * dataItem.txtPrice;
dataItem.txtPriceNum1 = mulFloat(dataItem.txtReturnNum, dataItem.txtPricetax);
})
$("#AddGrid").data("kendoGrid").refresh();
return;
});
$(document).on('click', '.returnDel', function (e) {
if (nowStatus != 0) {
return;
}
var ds2 = $("#AddGrid").data("kendoGrid").dataSource;
var row = $(this).closest("tr"),
grid = $("#AddGrid").data("kendoGrid"),
dataItem = grid.dataItem(row);
debugger;
ds2.fetch(function () {
dataItem.txtReturnNum = dataItem.txtReturnNum - (1);
dataItem.txtPriceNum = dataItem.txtReturnNum * dataItem.txtPrice;
dataItem.txtPriceNum1 = mulFloat(dataItem.txtReturnNum, dataItem.txtPricetax);
})
$("#AddGrid").data("kendoGrid").refresh();
return;
});
I'm not sure If i does not described correctly,so i record video
https://imgur.com/mePv5qI
How can i do will be correct
Why are you using fetch()? It seems that you don't need it, since you're not updating data from api. You're only updating local data, right ? So remove it and change dataItem directly:
var row = $(this).closest("tr"),
grid = $("#AddGrid").data("kendoGrid"),
dataItem = grid.dataItem(row);
dataItem.txtReturnNum = dataItem.txtReturnNum - (-1);
dataItem.txtPriceNum = dataItem.txtReturnNum * dataItem.txtPrice;
dataItem.txtPriceNum1 = mulFloat(dataItem.txtReturnNum, dataItem.txtPricetax);
$("#AddGrid").data("kendoGrid").refresh();
Or
var row = $(this).closest("tr"),
grid = $("#AddGrid").data("kendoGrid"),
dataItem = grid.dataItem(row);
dataItem.set('txtReturnNum', dataItem.txtReturnNum - (-1));
dataItem.set('txtPriceNum', dataItem.txtReturnNum * dataItem.txtPrice);
dataItem.set('txtPriceNum1', mulFloat(dataItem.txtReturnNum, dataItem.txtPricetax));

KendoUI filterable display internal error status:500

I am currently making some modifications on an application developed by someone else. The application uses the KendUI to render data on a grid. By default, the assumption would have been that the grid should be able to do filters and sort. When I turned the grid filters on and chose specific fields to filter by, I get status 500 error;
GET http://localhost/RFG/Workpermits?take=10&skip=0&page=1&pageSize=10&filter%5Blogic%5D=and&filter%5Bfilters%5D%5B0%5D%5Bfield%5D=Id&filter%5Bfilters%5D%5B0%5D%5Boperator%5D=eq&filter%5Bfilters%5D%5B0%5D%5Bvalue%5D=7&filter%5Bfilters%5D%5B1%5D%5Bfield%5D=ContractorName&filter%5Bfilters%5D%5B1%5D%5Boperator%5D=contains&filter%5Bfilters%5D%5B1%5D%5Bvalue%5D=Sor 500 (Internal Server Error)
Here is the piece of codes being used.
var workPermitsListView = new WorkPermitsListView();
$(document).ready(function () {
workPermitsListView.initializeControls();
var kgrid = $("#workPermitsGrid").data("kendoGrid");
var oldOptions = kgrid.getOptions();
var options = localStorage["kendo-grid-options"];
if (options) {
var savedOptions = JSON.parse(options);
var editFunc = oldOptions.columns[0];
savedOptions.columns[0] = editFunc;
kgrid.setOptions(savedOptions);
kgrid.dataSource.read();
}
});
function WorkPermitsListView() {
this.initializeControls = function () {
var url = window.location.href.slice(window.location.href.indexOf('?') + 1);
if (url == "refresh=true") {
window.location = window.location;
window.location = "WorkPermitsList.aspx";
} else if (url == "refresh=false") {
window.location = window.location;
}
$("#addWorkPermitBtn").on("click", function (e) { e.preventDefault(); workPermitsListView.createNewWorkPermit(); });
$("#omniSearchAdvTxt").keypress(function (e) { if (e.keyCode === 13) { $("#advSearchWorkPermitBtn").click(); } });
$("#omniSearchWorkPermitID").keypress(function (e) { if (e.keyCode === 13) { $("#advSearchWorkPermitBtn").click(); } });
$("#omniSearchLocation").keypress(function (e) { if (e.keyCode === 13) { $("#advSearchWorkPermitBtn").click(); } });
// $("#addWorkPermitBtn").kendoButton().data("kendoButton").enable(secScriptObj.canWriteWorkPermit);
if (!secScriptObj.canWriteWorkPermit) {
$("#addWorkPermitBtn").hide();
}
else {
$("#addWorkPermitBtn").kendoButton().data("kendoButton").visible = true;
$("#addWorkPermitBtn").kendoButton().data("kendoButton").enable(secScriptObj.canWriteWorkPermit);
}
var gridDefaultActionName = secScriptObj.canWriteWorkPermit ? "Edit" : "View";
var gridDataSource = new kendo.data.DataSource(
{
transport: { read: PTWApp.getSitePrefix() + "/Workpermits" },
pageSize: 10,
serverPaging: true,
serverFiltering: true,
serverSorting: true,
schema: {
total: "total",
data: "data",
model: {
id: "Id"
}
}
}
);
//var options = localStorage["grid-options"];
$("#workPermitsGrid").kendoGrid({
autoBind: false,
dataSource: gridDataSource,
scrollable: true,
sortable: true,
dataBound: WorkPermitsListView.onDataBind,
pageable: {
input: true,
numeric: false
},
noRecords: { template: "<div class='noRecordsDiv'>No permits to display. Use search for more or contact the administrator for assistance.</div>" },
filterable: true,
schema:{
model:{
fields:{
Id:{type:"int"},
StartDate:{type:"date"},
EndDate:{type:"date"}
}
}
},
columns: [
{
command: {
click: WorkPermitsListView.editWorkPermit,
name: "modify",
text: gridDefaultActionName
},
width: "70px"
},
{
field: "Id",
title: "Permit #",
width: "7%" ,
headerAttributes: { style: "white-space: normal"}
},
{
field: "Status",
title: "Status",
template: "#= WorkPermitsListView.addStatusImg(data)#",
width: "7%",
filterable:false,
headerAttributes: { style: "white-space: normal"},
editor: workPermitsListView.selectPermit
},
{
field: "StartDate",
title: "Start Date",
template: "#= PTWApp.ConvertDate(data.StartDate)#",
width: "7.5%",
filterable:false,
headerAttributes: { style: "white-space: normal"}
},
{
field: "EndDate",
title: "End Date",
template: "#= PTWApp.ConvertDate(data.EndDate)#",
width: "7.5%",
filterable:false,
format:"{0:MMM dd yyyy}",
headerAttributes: { style: "white-space: normal"}
},
{
field: "ContractorName",
title: "Contractor",
width: "8.5%",
headerAttributes: { style: "white-space: normal"}
},
{
field: "ContractorSupervisorName",
title: "Supervisor",
width: "8.5%",
filterable:false,
headerAttributes: { style: "white-space: normal"}
},
{
field: "ContractorSupervisorPhone",
title: "Phone #",
template: "#: WorkPermitsListView.formatPhone(ContractorSupervisorPhone) #",
width: "7.5%",
filterable:false,
headerAttributes: { style: "white-space: normal"}
},
{
field: "RequestedBy",
title: "Requester",
width: "7.5%",
filterable:false
},
{
field: "Attachments",
title: "Files",
template: "#= WorkPermitsListView.addFileImg(data)#",
filterable:false,
width: "6%"
},
{
field: "IsEvent",
title: "Events",
template: "#= WorkPermitsListView.addEventImg(data)#",
width: "5.5%"
},
{
field: "Description",
title: "Work Description",
width: "33.5%"
//, attributes: { "class": "shortText" } }
}
]
});
/** var grid = $("#workPermitsGrid").data("kendoGrid");
var selected = {};
if (options) {
workPermitsGrid.setOptions(JSON.parse(options));
}
windows.onbeforeunload = function () {
localStorage["grid-options"] = kendo.stringify(workPermitsGrid.getOptions());
return;
}
var grid = $("#workPermitsGrid").data("kendoGrid");
var selected = {};
var gridOptions = localStorage["kg-options"];
console.log(gridOptions);
if (gridOptions) {
grid.setOptions(JSON.parse(gridOptions));
}
else {
localStorage["kg-options"] = kendo.stringify(grid.getOptions());
}
**/
// attaches the tool tip to the cells
$(".shortText").kendoTooltip({
content: function (e) {
var target = e.target; // the element for which the tooltip is shown
return target.text(); // set the element text as content of the tooltip
}
});
gridDataSource.bind("error", function (error) { if (error.errors != undefined && error.errors.length > 0) { alertBox("Error:" + error.errors[0].error); } else { alertBox("Error fetching data: " + error.status); } });
$("#advSearchWorkPermitBtn").on("click", function () {
workPermitsListView.searchWorkPermit($("#omniSearchAdvTxt").val(), $("#omniSearchWorkPermitID").val(), $("#omniSearchContractor").val(), $("#workPermitStatusDropDown").val());
workPermitsListView.advancedSearchWindow.data("kendoWindow").close();
});
$(window).on("omniSearchTriggered", function (event, searchText) { workPermitsListView.searchWorkPermit(searchText, "", "", ""); });
$(window).on("AdvancedSearchClicked", function (event, searchText) { workPermitsListView.showAdvancedSearch(); });
if (this.getParameterValue('advsearch') === 'true') {
this.showAdvancedSearch();
}
else if (this.getParameterValue('omnisearch') !== undefined) {
searchText = this.getParameterValue('omnisearch')
$("#omniSearchTextBox").val(searchText);
this.searchWorkPermit(searchText, "", "", "");
}
else {
var grid = $("#workPermitsGrid").data("kendoGrid");
grid.dataSource.read();
}
}
WorkPermitsListView.formatPhone = function (phone)
{
return phone.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');
}
/** Redirects the browser to the work permit edit page
*
* #param sender object reference to the kendo grid
* #returns nothing
*/
WorkPermitsListView.editWorkPermit = function (e) {
e.preventDefault();
var data = this.dataItem($(e.currentTarget).closest("tr"));
window.location = 'WorkPermit.aspx?pid=' + data.Id;
}
/** Returns a status image
*
* #param model object reference to the work permit model
* #returns Html with img tag set to the right status image
*/
WorkPermitsListView.addStatusImg = function (model) {
if (model.Status === 2) {
return '<img src="../img/open_wp_status.png" class="statusIcon"/> In Progress';
}
else if (model.Status === 3) {
return '<img src="../img/closed_wp_status.png" class="statusIcon"/> Rejected';
}
else if (model.Status === 4) {
return '<img src="../img/cancelled_wp_status.png" class="statusIcon"/> Cancelled';
}
else if (model.Status === 5 ) {
return '<img src="../img/expired_wp_status.png" class="statusIcon"/> Expired';
}
if (model.Status === 6) {
return '<img src="../img/approved_wp_status.png" class="statusIcon"/> Approved';
}
}
/**
Get file attachment and display attachement icon
**/
WorkPermitsListView.addFileImg = function (model) {
var permitId = model.Id
return '<a href><img id="permitFile" src="../img/permit-attachment-icon.jpg" class="statusIcon" onclick="WorkPermitsListView.getPermitFile($(this))" ></a>';
}
WorkPermitsListView.getPermitFile = function (e) {
var grid = $("#workPermitsGrid").data("kendoGrid");
$(grid.tbody).on("click", "#permitFile", function (e)
{
var row = $(this).closest("tr");
var rowIndex = $("tr", grid.tbody).index(row);
var id = grid._data[rowIndex].Id;
$.ajax(
{
url: PTWApp.getSitePrefix() + '/File/GetWorkPermitFile',
type: 'GET',
dataType: 'json',
data:
{
workPermitId: id
},
success: function (data) {
var link = document.createElement('a');
document.body.appendChild(link);
link.href = PTWApp.getSitePrefix() + data.file.Url;
link.click();
},
error: function () {
alertBox("Error downloading");
}
});
});
}
WorkPermitsListView.onDataBind = function(arg) {
kgrid = $("#workPermitsGrid").data("kendoGrid");
localStorage["kendo-grid-options"] = JSON.stringify(kgrid.getOptions());
}
/** Returns an events checkmark image
*
* #param model object reference to the work permit model
* #returns Html with img tag set to the right status image
*/
WorkPermitsListView.addEventImg = function (model)
{
if (model.IsEvent === true)
{
return '<img src="../img/checkmark.png" class="statusIcon" style=" display: block; margin-left: auto; margin-right: auto; width: 20%"/>'
}
else
{
return '';
}
}
/** Triggers a work permit search using the parameters as criteria
*
* #param ominisearch string text typed by the user
*
* #param includeContractorActivePermitsOnly bool tells the search if the user wants to retrieve only contractors with active permits
*
* #param includeInactiveContractors bool tells the search if the user wants to include inactive/deleted contractors in the search
*
* #returns nothing
*/
this.searchWorkPermit = function (omnisearch,workPermitID,contractorName,status)
{
if (status === null ||
status === "")
{
status = PTWApp.EnumWorkPermitStatus.Undefined; // default status
}
console.log("Omnisearch: "+omnisearch + " | contractorID: "+ contractorName + " | WorkPermitID: "+workPermitID + " | Status: "+status);
var grid = $("#workPermitsGrid").data("kendoGrid");
grid.dataSource.query({
page: 1,
pageSize: 10,
serverPaging: true,
serverFiltering: true,
serverSorting: false,
filter: {
"omnisearch": omnisearch,
"workPermitID": workPermitID,
"contractorID": contractorID,
"status": status
}
/** logic: "and",
filter: [
{field: "Id", operator: "eq", value: workPermitID},
{field: "ContractorName", operator: "contains", value: contractorName},
{field: "Status", operator: "eq", value: status}
] **/
});
$(".searchContextInfo").text("Search results");
}
/** Retrieves a parameter value from the query string (url)
*
* #param param string parameter name to look for
*
* #return string Returns the parameter value if found
*/
this.getParameterValue = function (param)
{
var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < url.length; i++) {
var urlparam = url[i].split('=');
if (urlparam[0] == param) {
return urlparam[1];
}
}
}
/** Displays the advanced search div
*
* #param none
*
* #return none
*/
this.showAdvancedSearch = function ()
{
this.advancedSearchWindow = $("#advancedSearchDiv");
this.advancedSearchWindow.kendoWindow(
{
width: 370,
height: 320,
title: "Advanced Work Permit Search",
visible: false,
modal: true,
actions: ["Close"]
}
);
this.advancedSearchWindow.data("kendoWindow").center().open();
}
/** Creates an AJAX request to save the new work permit information
*
* #param none
*
* #return none
*/
this.createNewWorkPermit = function ()
{
window.location = 'WorkPermit.aspx?pid=-1';
}
Can someone please help me identify what is wrong?
I can see that you have configured the grid to use 'serverFiltering', also you're using two different configurations, the first with a variable and then inside the grid config itself, I would recomend to only use one, I've udpated your grid config to this:
$("#workPermitsGrid").kendoGrid({
autoBind: false,
dataSource: {
transport: { read: PTWApp.getSitePrefix() + "/Workpermits" },
schema:{
model:{
id: "Id",
fields:{
Id:{type:"number" },
StartDate:{type:"date" },
EndDate:{type:"date" }
}
}
},
pageSize: 10,
},
scrollable: {
virtual: true
},
sortable: true,
dataBound: WorkPermitsListView.onDataBind,
pageable: {
numeric: false,
previousNext: false
},
noRecords: { template: "<div class='noRecordsDiv'>No permits to display. Use search for more or contact the administrator for assistance.</div>" },
filterable: true,
columns: [
{
command: {
click: WorkPermitsListView.editWorkPermit,
name: "modify",
text: gridDefaultActionName
},
width: "70px"
},
{
field: "Id",
title: "Permit #",
width: "7%" ,
headerAttributes: { style: "white-space: normal"}
},
{
field: "Status",
title: "Status",
template: "#= WorkPermitsListView.addStatusImg(data)#",
width: "7%",
filterable:false,
headerAttributes: { style: "white-space: normal"},
editor: workPermitsListView.selectPermit
},
{
field: "StartDate",
title: "Start Date",
template: "#= PTWApp.ConvertDate(data.StartDate)#",
width: "7.5%",
filterable:false,
headerAttributes: { style: "white-space: normal"}
},
{
field: "EndDate",
title: "End Date",
template: "#= PTWApp.ConvertDate(data.EndDate)#",
width: "7.5%",
filterable:false,
format:"{0:MMM dd yyyy}",
headerAttributes: { style: "white-space: normal"}
},
{
field: "ContractorName",
title: "Contractor",
width: "8.5%",
headerAttributes: { style: "white-space: normal"}
},
{
field: "ContractorSupervisorName",
title: "Supervisor",
width: "8.5%",
filterable:false,
headerAttributes: { style: "white-space: normal"}
},
{
field: "ContractorSupervisorPhone",
title: "Phone #",
template: "#: WorkPermitsListView.formatPhone(ContractorSupervisorPhone) #",
width: "7.5%",
filterable:false,
headerAttributes: { style: "white-space: normal"}
},
{
field: "RequestedBy",
title: "Requester",
width: "7.5%",
filterable:false
},
{
field: "Attachments",
title: "Files",
template: "#= WorkPermitsListView.addFileImg(data)#",
filterable:false,
width: "6%"
},
{
field: "IsEvent",
title: "Events",
template: "#= WorkPermitsListView.addEventImg(data)#",
width: "5.5%"
},
{
field: "Description",
title: "Work Description",
width: "33.5%"
//, attributes: { "class": "shortText" } }
}
]
});
Try it and let me know if it works.

Kendo grid insert new row with custom class

This is how I insert new data to kendo grid, however i want my added row have a custom class, so I can style my new added row with different background color. How can I achieve this ? I searching all the doc can't find any related
var dataSource = $('#grid').data('kendoGrid').dataSource;
dataSource.insert(0, {
"name":"ABC",
"age": 99
});
In order to add a new class to each newly row you can use .addClass(). But, every time you move to the next/prev page or add other rows you need to add again the class....
In order to achieve that you can save in a global array a list of all newly added row uuid and on dataBound event reapply the class.
Fiddle here
var newUUID = [];
$("#grid").kendoGrid({
navigatable: true,
filterable: true,
pageable: {
pageSize: 5,
alwaysVisible: false,
pageSizes: [5, 10, 20, 100]
},
dataBound: function(e) {
$.each(newUUID, function(idx, ele) {
if ($(ele).length != 0) {
$(ele).addClass('newRow');
}
})
}
});
$('#btn').on('click', function(e) {
var dataSource = $('#grid').data('kendoGrid').dataSource;
var x = dataSource.insert(0, {
"name":"ABC",
"age": 99
});
newUUID.push("[data-uid='" + x.uid + "']");
$("[data-uid='" + x.uid + "']").addClass('newRow');
})
You can look-up the newly added row by its UID and add the class to the row.
I explored the solution on this blog: "Simple Row Coloring in a KendoUI Grid"
const sampleData = getSampleData();
$(document).ready(() => {
$("#example-grid-wrapper").kendoGrid({
dataSource: {
data: sampleData.data,
schema: {
model: {
fields: sampleData.fields
}
}
},
columns: sampleData.columns
});
setTimeout(insertNewRecordAfterOneSecond, 1000);
});
function insertNewRecordAfterOneSecond() {
// Insert data
let dataGrid = $('#example-grid-wrapper').data('kendoGrid');
dataGrid.dataSource.insert(0, { id: 1, name: "Sam", location: "B", color: "blue", status: 0 });
// Re-scan table and lookup newly added row.
dataGrid = $('#example-grid-wrapper').data('kendoGrid');
let dataView = dataGrid.dataSource.view();
for (let i = 0; i < dataView.length; i++) {
if (dataView[i].id === 1) {
dataGrid.table.find("tr[data-uid='" + dataView[i].uid + "']").addClass("highlighted-row");
}
}
}
function getSampleData() {
return {
data : [
{ id: 2, name: "Grant", location: "A", color: "green", status: 1 },
{ id: 3, name: "Vaughan", location: "B", color: "red", status: 0 },
{ id: 4, name: "David", location: "A", color: "orange", status: 1 }
],
fields : {
id: { type: "number" },
name: { type: "string" },
location: { type: "string" },
color: { type: "string" }
},
columns : [
{ field: "id", title: "ID", width: "10%" },
{ field: "name", title: "Name", width: "30%" },
{ field: "location", title: "Location", width: "30%" },
{ field: "color", title: "Color", width: "20%" },
{ field: "status", title: "Status", width: "10%" }
]
};
}
.highlighted-row {
background: #FF0; /* Higlight row yellow */
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://kendo.cdn.telerik.com/2019.2.619/js/kendo.all.min.js"></script>
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2019.2.619/styles/kendo.common.min.css" />
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2019.2.619/styles/kendo.blueopal.min.css" />
<div id="example-grid-wrapper">
<div id="example-grid"></div>
</div>
Alternative
As suggested by gaetanoM.
const sampleData = getSampleData();
var insertedUidList = [];
$(document).ready(() => {
$("#example-grid").kendoGrid({
dataSource: {
data: sampleData.data,
schema: {
model: {
fields: sampleData.fields
}
}
},
columns: sampleData.columns,
// Suggested by gaetanoM
dataBound: function(e) {
$.each(insertedUidList, function(idx, uid) {
// Re-apply class to existing rows.
$(`tr[data-uid="${uid}"]`).addClass('highlighted-row');
});
}
});
// Insert two rows, one second apart.
insertRowsWithDelay([
{ id: 0, name: "Joseph", location: "A", color: "yellow", status: 1 },
{ id: 1, name: "Sam", location: "B", color: "blue", status: 0 },
], 1000)
});
function insertRowsWithDelay(data, delayBetween) {
if (data == null || data.length === 0) return;
setTimeout(() => {
insertNewRecord(data.pop());
insertRowsWithDelay(data, delayBetween);
}, 1000);
}
function insertNewRecord(record) {
record = $('#example-grid').data('kendoGrid').dataSource.insert(0, record);
insertedUidList.push(record.uid);
$(`[data-uid="${record.uid}"]`).addClass('highlighted-row');
}
function getSampleData() {
return {
data : [
{ id: 2, name: "Grant", location: "A", color: "green", status: 1 },
{ id: 3, name: "Vaughan", location: "B", color: "red", status: 0 },
{ id: 4, name: "David", location: "A", color: "orange", status: 1 }
],
fields : {
id: { type: "number" },
name: { type: "string" },
location: { type: "string" },
color: { type: "string" }
},
columns : [
{ field: "id", title: "ID", width: "10%" },
{ field: "name", title: "Name", width: "30%" },
{ field: "location", title: "Location", width: "30%" },
{ field: "color", title: "Color", width: "20%" },
{ field: "status", title: "Status", width: "10%" }
]
};
}
.highlighted-row {
background: #FF0; /* Higlight row yellow */
}
.highlighted-row.k-alt {
background: #DD0; /* Higlight row yellow */
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://kendo.cdn.telerik.com/2019.2.619/js/kendo.all.min.js"></script>
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2019.2.619/styles/kendo.common.min.css" />
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2019.2.619/styles/kendo.blueopal.min.css" />
<div id="example-grid"></div>
You can try to create a databound function for the grid and then try this inside the function
function onDataBound(e) {
var dataSource = $("#GridName").data("kendoGrid").dataSource;
var data = dataSource.data();
$.each(data, function (index, rowItem) {
if (data.length > 0) {
var rows = e.sender.tbody.children();
var row = $(rows[index]);
if (data[index].name == "ABC" ) {
row.addClass("NameColor");
}
}
});
}
<style>
.NameColor {
background-color: black;
}
</style>
Like this you can try..

Alert selective datafield in jQWidget Grid on hyperlink click event

I am working on JQWidget grid. In each row I have record ID along with other fields
there is two things I want to do, (I have done first part, code been updated... is anyone know about part 2 of this question????)
1- make name column in row hyperlink
2- when column cell with hyperlink click, script read the ID of record which in my case 'dataField =StudentDBID' and alert these information.
function BindStudentListToGrid(data)
{
var DataSource =
{
datatype: "json",
datafields: [
{ name : 'StudentDBID'},
{ name: 'RelationshipID' },
{ name: 'Studentid' },
{ name: 'Unite_id'},
{ name: 'Date_start' },
{ name: 'Date_end' },
{ name: 'FullName' },
{ name: 'Locality' }
],
id: 'ID',
localdata: data,
async: false,
};
var dataAdapter = new $.jqx.dataAdapter(DataSource);
$("#StudentListInRelationToStaffGrid").jqxGrid(
{
source: dataAdapter,
theme: 'classic',
width: '100%',
sortable: true,
pagesize: 2,
pageable: true,
autoheight: true,
columns: [
{ text: 'StudentDB ID', datafield: 'StudentDBID', hidden: true },
{ text: 'Relationship ID', datafield: 'RelationshipID', hidden: true },
{ text: 'Student ID', datafield: 'Studentid', hidden: true },
{ text: 'Unite ID', datafield: 'Unite_id', hidden: true },
{ text: 'From', datafield: 'Date_start', width: 200 },
{ text: 'To', datafield: 'Date_end', width: 200 },
{ text: 'Name', datafield: 'FullName', cellsrenderer: linkrenderer },
{ text: 'Locality', datafield: 'Locality' }
]
});
}
var linkrenderer = function (row, column, value) {
return "<a href=#>" + value + "</a>";
}
$('#StudentListInRelationToStaffGrid').on('cellclick', function (event) {
if (event.args.datafield == "FullName")
{
alert("A cell has been clicked:" + event.args.rowindex + ":" + event.args.datafield + event.args.value );
}
});
my data is coming in json format
In order word, how can read column field by row index as I can get that using click event???
here is complete answer
$("#StudentListInRelationToStaffGrid").jqxGrid(
{
source: dataAdapter,
theme: 'classic',
width: '100%',
sortable: true,
pagesize: 2,
pageable: true,
autoheight: true,
columns: [
{ text: 'StudentDB ID', datafield: 'StudentDBID', hidden: true },
{ text: 'Relationship ID', datafield: 'RelationshipID', hidden: true },
{ text: 'Student ID', datafield: 'Studentid', hidden: true },
{ text: 'Unite ID', datafield: 'Unite_id', hidden: true },
{ text: 'From', datafield: 'Date_start', width: 200 },
{ text: 'To', datafield: 'Date_end', width: 200 },
{ text: 'Name', datafield: 'FullName', cellsrenderer: linkrenderer },
{ text: 'Locality', datafield: 'Locality' }
]
});
}
var linkrenderer = function (row, column, value) {
return "<a href=#>" + value + "</a>";
}
$('#StudentListInRelationToStaffGrid').on('cellclick', function (event) {
if (event.args.datafield == "FullName")
{
alert("A cell has been clicked:" + event.args.rowindex + ":" + event.args.datafield + event.args.value);
var datarow = $('#StudentListInRelationToStaffGrid').jqxGrid('getrowdata', event.args.rowindex);
alert(datarow.StudentDBID);
}
});

Kendo UI Grid Refesh on Dropdown Selection

I have a grid where each row has a select drop down box in with values.
When an item is selected, how can I make the grid reload to reflect the change?
The reason I want to do this is because the item selected from the drop down effects an amount in another column.
Here is the code for my dropdown:
function shippingModelSelect(container, options)
{
$('<input required data-text-field="modelName" data-value-field="modelId" data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
autoBind: false,
dataSource: [
{
"modelName": "Individual shipping cost",
"modelId": 1
},
{
"modelName": "Based on weight",
"modelId": 2
},
{
"modelName": "Based on value",
"modelId": 3
}
],
close: function()
{
handleChange();
}
});
}
My handle change function:
var gridAlert = $('#gridAlert');
var handleChange = function(input, value) {
if(input && value)
{
detail = 'Product <b>'+input[0].name+'</b> changed to <b>'+value+'</b>';
gridAlert.html('<b>Changes saved!</b><p>'+detail+'</p>');
gridAlert.fadeIn('slow', function(){
setTimeout(function(){
gridAlert.fadeOut();
}, 2000)
});
}
dataSource.sync();
}
And finally my grid setup:
dataSource = new kendo.data.DataSource({
serverPaging: true,
serverSorting: true,
serverFiltering: true,
serverGrouping: true,
serverAggregates: true,
transport: {
read: {
url: ROOT+'products/manage'
},
update: {
url: ROOT+'products/set-product',
type: "POST",
data: function(data)
{
data.dateAdded = kendo.toString(data.dateAdded, 'yyyy-MM-dd hh:ii:ss')
return data;
}
}
},
pageSize: 20,
sort: {
field: 'id',
dir: 'desc'
},
error: function(e) {
alert(e.errorThrown+"\n"+e.status+"\n"+e.xhr.responseText) ;
},
schema: {
data: "data",
total: "rowcount",
model: {
id: "id",
fields: {
id: {
type: 'number',
editable: false
},
SKU: {
type: "string"
},
name: {
type: "string"
},
dateAdded: {
type: "date",
format: "{0:yyyy/MM/dd hh:mm}",
editable: false
},
shippingModel: {
type: "string"
},
shippingModelId: {
type: "number"
},
price: {
type: "number"
}
}
}
}
})
$('#productGrid').kendoGrid({
dataSource: dataSource,
autoBind: true,
columns: [
{
field: "image",
title: "Image",
width: 30,
template: "#= '<img title=\"'+alt+'\" src=\"images/'+image+'\"/>' #"
},
{
field: "SKU",
title: "SKU",
width: 50,
headerTemplate: "<abbr title=\"Stock Keeping Unit - A unique identifier for this product\">SKU</abbr>"
},
{
field: "stockQuantity",
title: "Quantity",
width: 30
},
{
field: "name",
title: "Name",
width: 200
},
{
field: "dateAdded",
title: "Date Added",
width: 80,
template: "#= niceDate #"
},
{
field: "shippingModelId",
title: "Shipping Model",
width: 50,
editor: shippingModelSelect,
template: "#= shippingModel #"
},
{
field: "price",
title: "Price",
width: 80,
//format: "{0:c}",
template: "#= '£'+price.toFixed(2)+'<br /><span class=\"grey\">+£'+shipping+' shipping</span>' #"
}
],
sortable: true,
editable: true,
pageable: {
refresh: true,
pageSizes: [10, 20, 50]
},
scrollable: false,
reorderable: true,
edit: function(e) {
var value;
var numericInput = e.container.find("[data-type='number']");
// Handle numeric
if (numericInput.length > 0)
{
var numeric = numericInput.data("kendoNumericTextBox");
numeric.bind("change", function(e) {
value = this.value();
handleChange(numericInput, value);
});
return;
}
var input = e.container.find(":input");
// Handle checkbox
if (input.is(":checkbox"))
{
value = input.is(":checked");
input.change(function(){
value = input.is(":checked");
handleChange(input, value);
});
}
else
{
// Handle text
value = input.val();
input.keyup(function(){
value = input.val();
});
input.change(function(){
value = input.val();
});
input.blur(function(){
handleChange(input, value);
});
}
}
}
)
You will need to do two things.
Wait for changes to finish syncing
Tell the grid to re-read the datasource
This should do both for you
dataSource.bind("sync", function(e) {
$('#productGrid').data("kendoGrid").dataSource.read();
});
For more info see the datasource sync event and datasource read method on their docs site.

Categories

Resources