How can I set a max-width property to individual kendo grid columns? - javascript

Here's a jsfiddle with a sample kendo grid:
http://jsfiddle.net/owlstack/Sbb5Z/1619/
Here's where I set the kendo columns:
$(document).ready(function () {
var grid = $("#grid").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,
scrollable: true,
sortable: true,
selectable: true,
change: onChangeSelection,
filterable: true,
pageable: true,
columns: [{
field: "FirstName",
title: "First Name",
width: "100px",
}, {
field: "LastName",
title: "Last Name",
width: "100px",
}, {
field: "City",
width: "100px",
}, {
field: "Title",
width: "105px"
}, {
field: "BirthDate",
title: "Birth Date",
template: '#= kendo.toString(BirthDate,"MM/dd/yyyy") #',
width: "90px"
}, {
field: "Age",
width: "50px"
}]
}).data("kendoGrid");
applyTooltip();
});
I added individual widths to each of the columns. However, I would also like to set a max-width to each kendo grid column. Is it possible to set a max-width (not a set one for all columns but max-width for individual columns?)?

There is no property like max-width exposed for kendo grid. One of the round about solution will be to set Width of Column as autosize and then use template where you use css properties to maintain max width.
Following is the example. Not sure if you are looking for the same answer.
<style>.intro { max-width: 100px ;width: 20px ;background-color: yellow;</style>
<script>
$(document).ready(function () {
$("#grid").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "http://demos.telerik.com/kendo-ui/service/Northwind.svc/Customers"
},
pageSize: 20
},
height: 550,
groupable: true,
sortable: true,
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
columns: [{
field: "ContactName",
title: "Contact Name",
template : '<span class=intro>#:ContactName#</span>'
}, {
field: "ContactTitle",
title: "Contact Title"
}, {
field: "CompanyName",
title: "Company Name"
}, {
field: "Country",
width: 150
}]
});
});
</script>

I have JavaScript code that will help achieve this functionality. It provides a way for a (command) column to retain a fixed size.
On the one hand, it acts as a minimum size for a column, but if the grid were to increase in size, the original size is enforced. This allows for other grid cells to increase in size by a larger amount.
Check out this dojo that shows this code in action.
Note that all columns need to have a specified width (this effectively becomes a minimum width).
The browser resize event is used to trigger the size recalculation of the grids.
This function supports master/detail and grouping.
I have not considered column resizing at this point.
If you have any ideas for improvements then go for it!

.k-grid td
white-space: nowrap;
text-overflow: ellipsis;
max-width:150px;
}

YES....
You can set a textbox-style MAX WIDTH for column values in a Kendo Grid...and you can do a lot more too. However, you must do so by-hand using the grids Before Edit event.
FOR EXAMPLE:
// ELEMENTS
var $gridDiscipline = $('#gridDiscipline')
var grid = $gridDiscipline.kendoGrid();
// EVENTS
grid.bind('beforeEdit', beforeEdit);
// IMPLEMENTATION
function beforeEdit(e)
{
// Edit Master Row
// This event raises when ADD_NEW or EDIT is pressed
// Optionally, I add a slight timeout to ensure the MASTER ROW is "open"
// Obviously, the elements in your row will be different from mine
// As you will see...you can do all kinds of late-bound configuration practices here (whatever makes sense for you)
setTimeout(function () {
var $container = $('.k-master-row', e.sender.tbody);
// Elements
var $cmbContactEmployee = $container.find("#EmployeeId");
var $txtDisciplineName = $container.find("#DisciplineName");
var $txtTags = $container.find("#Tags");
// Instances
var cmbContactEmployee = $cmbContactEmployee.data('kendoComboBox');
// Configuration
cmbContactEmployee.dataSource.transport.options.read.data = function (e) {
var text = e.filter.filters[0].value;
return { searchText: text };
};
// If a DataAnnotation value exists...you can enforce it
var maxlength = $txtDisciplineName.attr('data-val-length-max');
if (maxlength) {
$txtDisciplineName.attr('maxlength', maxlength);
}
// Or you can set something outright
$txtTags.attr('maxlength', 100);
}, 500);
}

Related

w2ui grid hide and show not working properly

I am working on w2ui grid and I need to hide and show it based on certain condition. Grid is not showing back even though visibility:visible property is applied after it is hidden. It is just showing a line.
Please have a look at my code below:
HTML:
<div id="LastMileGrid" class="col-lg-6 col-sm-12 col-md-6" style="width: 100%; height: 150px"></div>
Javascript:
$('#LastMileGrid').w2grid({
name: 'LastMile',
show: {
toolbar: true,
footer: true,
toolbarReload: false,
toolbarColumns: false,
lineNumbers: true,
},
columns: [
{ field: 'recid', caption: 'ID', size: '10%', sortable: true },
//{ field: 'Header', caption: 'Header', size: '20%', editable: { type: 'text' }, sortable: true },
{ field: 'Description', caption: 'Description', size: '50%', editable: { type: 'text' }, sortable: true }
],
toolbar: {
items: [
{ id: 'add', type: 'button', caption: 'Add Record', icon: 'w2ui-icon-plus' },
{ id: 'remove', type: 'button', caption: 'Remove Record', icon: 'w2ui-icon-cross' }
],
onClick: function (event) {
if (event.target == 'add') {
var Index = w2ui['LastMile'].records.length;
w2ui['LastMile'].add({ recid: w2ui['LastMile'].records.length + 1 });
}
if (event.target == 'remove') {
var grid = w2ui["LastMile"];
grid.method = 'DELETE';
grid.delete();
}
}
},
//records: [{ recid: 'AAA' }, { recid: 'BBB' }, { recid: 'CCC' }]
});
And when opening the pop up I call the function,
$('#popup').w2popup('open', {
onOpen: function () {
if ($("#ddlMode").val() == "AIR" && ($("#drpServiceScope").val() == "D2D" || $("#drpServiceScope").val() == "A2D")) {
$('#LastMileGrid').attr("style", "visibility:visible;height:160px:")
}
else {
$('#LastMileGrid').attr("style", "visibility:collapse;")
}
},
modal: true,
});
You can try to call w2ui["LastMile"].refresh() after hiding or showing.
Answering to help others as I am late :D.
After spending a lot of time to resolve the issue,I have formulize below 2 solutions for w2ui grid show hide issue or column size issue :
1.Change the size of columns to px instead of %.
ie. use
{ field: 'lname', caption: 'Last Name', size: '30px' }
instead of
{ field: 'lname', caption: 'Last Name', size: '30%' },
2. If you wish to keep column size in % due to some requirement:
Depending on where you are rendering grid,you need to handle the resizing.
Calling refresh on grid will send data request again to server.
I don't wanted grid to make call to server each time I show/hide grid, hence written the resize of my own.
To help understand the function please note that in my application,
I have followed naming convention as follows:
If I create a grid then it will be id+"_grid",
If create a form that it will be id+"_form",
same for layout id+"_layout".
So I can get the associated component to a id and establish relation between them.
Call resize() function after you call show().
If below function doesn't help, try adding some milli seconds delay between show and my function resize().
function resize(id){
var grid=id+"_grid";
var layout=id+"_layout";
var form=id+"_form";
if(w2ui[layout]){
if($(w2ui[layout].el("main")).hasClass("w2ui-grid")){ /*means in w2ui layouts main has grid hence call resize. Calling refresh on layout "main" will make grid to reload data again ,hence grid resizing is handled in next case */
w2ui[layout].resize();
}else{
w2ui[layout].refresh();/*means main has element other than grid so refresh */
}
}
if(w2ui[form])
w2ui[form].resize();
if(w2ui[grid])
w2ui[grid].resize(); //if grid is directly rendered without a layout resize helps
}

How to expand a kendo grid on clicking a column value using angular js

I am trying to use Kendo UI Grid with angular js. I need to expand the grid to further level when user clicks a link given in one of the columns of the grid.
I used following code to expand the grid on click of an tag inside a kendo grid column.
$scope.mainGridOptions = {
dataSource: {
data: $scope.data,
schema: {
model: {
fields: {
fieldA: { type: "string" },
fieldB: { type: "string" },
fieldC: { type: "string" },
fieldT: { type: "numeric" }
}
}
},
pageSize: 10
},
filterable: true,
sortable: true,
resizable: true,
pageable: true,
scrollable: true,
columns: [
{ field: "fieldA", title: "FieldA", width: 90},
{ field: "fieldB", title: "FieldB", width: 90},
{ field: "fieldC", title: "FieldC", width: 90},
{ field: "fieldT", title: "FieldT", width: 90, template: "<a onclick='expand(this)'href='\\#'>#=mydata#</a>"}
]
};
But on running the code it just gives me an error in the browser console window.
Uncaught ReferenceError: expand is not defined at
HTMLAnchorElement.onclick
I researched and found that Kendo doesn't supports onclick event inside an tag. Therfore tried to use tag instead of tag. But it still does not work.
{ field: "fieldT", title: "FieldT", width: 90, template: "<span ng-click='showFileLevel(this)>{{mydata}}</span>"}
Can anyone please guide me in the right direction or let me know how can I expand a Kendo grid to further levels on clicking text inside a certain column of the grid using Angular JS.
you write expand(this) method out of the controller in your js.

Populate a column in Kendo Grid based on separate Datasource

I have a kendo grid like what I've posted below. I'm populating the grid based on the data in the url I provided for it. However, there is one column on the grid, the flag column, which I would like to be a separate datasource to populate that column, based on the id. The datasource for that column would look something like:
[{id:1234, flag: 'N'}, {id:5678, flag:'Y'}]
Is there a way where I can populate just 1 column in the grid based on a completely different datasource from the rest of the grid? The flag would need to be placed on the row of its corresponding id. If so, how can I implement this? Any help would be appreciated.
$("#grid").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: url
},
pageSize: 30
},
height: 400,
groupable: true,
sortable: true,
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
columns: [{
field: "id",
title: "ID",
width: 240
}, {
field: "FirstName",
title: "First Name"
}, {
field: "LastName",
title: "LastName"
}, {
field: "flag",
title: "Flag",
width: 150
}]
});
Consider using a foreign key column.
http://demos.telerik.com/kendo-ui/grid/foreignkeycolumn

How to Set Kendo grid height to a fixed value on page load

I am trying to get a Kendo grid with a static height and width.
It absolutely must not change height and width when I page (which it currently does, due to variably-sized data).
If data increases ,I should provide the Scrolling.
The problem is that when the page is first loading with Data the kendo grid is not setting to that fixed height and width.
but if I resize the window it is getting that fixed height and Providing the Scroll option inside Kendo Grid
So I can I set the height Of kendo Grid at a fixed value when it loads for first time
Kendo Version : v2014.1.318
Code:
$("#ViewUnitContainerTracking").kendoGrid({
sortable: true,
height:"280px",
columns: [
{
field: "UnitCode",
title: "Unit",
width: "15%"
},
{
field: "UnitName",
title: "Unit Name",
width: "35%"
},
{
field: "Status",
title: "St",
width: "5%",
template: $("#TemplateViewUnitTrackingStatus").text()
},
{
field: "StartDate",
title: "Start Date",
//template: $("#TemplateViewUnitTrackingStartDate").text(),
width: "15%",
//type: "date"
},
{
field: "EndDate",
title: "End Date",
//template: $("#TemplateViewUnitTrackingEndDate").text(),
width: "15%",
//type: "date"
},
{
field: "AssessPrgress",
title: "%OAP",
width: "10%"
},
{
field: "Status",
title: "Status",
hidden: true
}
],
editable: false,
resizable: false,
mobile: true,
dataSource: data.UnitList
});
Html Page:
<div id="ViewUnitContainerTracking" style="padding-top:10px;">
</div>
Answer of the problem is:-
dataBound: function() {
$('#ViewUnitContainerTracking .k-grid-content').height(280);
}
Adding this to the Kendo grid will Solve the issue.
As After Data Bound event we can set the custom Css property of the Grid as the Grid dynamic height is set previous to this event.
I m doing this dynamically, to set the Grid to 100%, means, minus bootstrap header and footer:
<script type="text/javascript">
var gridElement = $("#serviceGrid");
function resizeGrid() {
$("#serviceGrid").css("height", $(window).height() - $("#itheader").height() - $("#itfooter").height() - 2);
gridElement.data("kendoGrid").resize();
}
$(window).resize(function() {
resizeGrid();
});
</script>
The "- 2" is because of two 1px borders a top and bottom..
I find this more reliable option which works with locked/frozen columns as well. You can call below lines of code in window's resize event handler
var availableHeight = 500; // Calculate this value based on space available in grid's parent container
$('#YOUR_GRID_ID').data('kendoGrid').setOptions({ height: availableHeight})

Show Row Details as a Popup/ToopTip form on Mouse Hover for each row in KendoUI Grid

I have a grid populated with data and
i want to show only 3 or 2 columns and hide rest of columns cause the grid goes very wide.
when the mouse is hovered over a row i want to show all the columns of that row as as popup /tooltip form.
Please help me with this. I searched a lot and only found out Editable popup and with button click not with hover.
function PopulateGrid() {
$("#recentNews").kendoGrid({
columns: [
{ field: 'Date', title: 'Date', width: 80,
template: '#=kendo.toString(toDate(NewsDate), "yyyy/MMM/dd") #'
},
{ field: 'TradeTime', title: 'Time', width: 60,
template: '#=kendo.toString(toDate(NewsTime), "hh:mm:ss") #'
},
{ field: 'Title', title: 'Description', width: 200 },
{ field: 'Country', title: 'Country', width: 40 },
{ field: 'Economy', title: 'Economoy', width: 40 }
],
dataSource: {
transport: {
read: {
url: 'Home/GetNews',
dataType: "json",
type: "POST"
}
},
schema: {
data: function (data) {
return data.data;
},
total: function (data) {
return data.total;
}
},
pageSize: 100
},
// change: onChange,
// dataBound: onDataBound,
dataBound: HoverOnGrid,
pageable: true,
sortable: true,
scrollable: true,
height: 565,
width: 2000
});
}
There are two separate questions about what you are trying to implement:
Bind hover to the Grid rows (easy).
Generate a popup / tooltip that shows the rest of the columns (easy but requires some amount of coding).
Since it seems that you have already defined a function called HoverOnGrid lets write it as:
function HoverOnGrid() {
$("tr", "#recentNews").on("mouseover", function (ev) {
// Invoke display tooltip / edit row
var rowData = grid.dataItem(this);
if (rowData) {
showTooltip(rowData);
}
});
}
where grid is:
var grid = $("#recentNews").kendoGrid({
...
}).data("kendoGrid";
Now, the tricky question, how to show a tooltip / popup... There is no predefined way of doing it, you should do it by yourself. The closes that you can get is defining HoverOnGrid as:
function HoverOnGrid() {
$("tr", "#recentNews").on("click", function (ev) {
grid.editRow(this);
})
}
and the Grid initialization say:
editable: "popup",
But this opens a popup but with fields on edit mode (something that you can hack defining in the dataSource.schema.model that all fields are not editable:
model: {
fields: {
Date: { editable: false },
TradeTime: { editable: false },
Title: { editable: false },
Country: { editable: false },
Economy: { editable: false }
}
}
But it still shows update and cancel buttons in the popup.
So, my recommendation is writing a piece of code that creates that tooltip.
EDIT: For hiding the tooltip you should first intercept the mouseout event:
$("tr", "#recentNews").on("mouseout", function (ev) {
// Hide Tooltip
hideTooltip();
});
where hideTooltip might be something as simple as:
var tooltipWin = $("#tooltip_window_id").data("kendoWindow");
tooltipWin.close()
assuming that you are always using the same id for the tooltip (in this example, tooltip_window_id).

Categories

Resources