Kendo grid tooltip for unknown column - asp.net-mvc

I am using kendo grid and I would like to show a tooltip everytime the user perform a mouseover on any grid cell. The following example works fine, but what about if I don't know the column the user do mouseover?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Kendo UI Snippet</title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.2.516/styles/kendo.common.min.css"/>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.2.516/styles/kendo.rtl.min.css"/>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.2.516/styles/kendo.silver.min.css"/>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.2.516/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/2018.2.516/js/kendo.all.min.js">
</script>
</head>
<body>
<div id="grid"></div>
<style>
#grid{
width:300px;
}
</style>
<script>
var grid = null;
$(document).ready(function () {
var dataSource = new kendo.data.DataSource({
data: [
{ID:1 ,Text: "Text 1"},
{ID:2 ,Text: "Text 2"},
{ID:3 ,Text: "Text 3"}
],
schema: {
model: {
fields: {
ID: { type: "number" },
Text: { type: "string" }
}}
},
pageSize: 20
});
grid = $("#grid").kendoGrid({
dataSource: dataSource,
scrollable: true,
filterable: true,
toolbar: ["create"],
columns: [
{ field: "ID", width: "50px" },
{ field: "Text", width: "200px", attributes: {
style: 'white-space: nowrap '
} }],
editable: "incell"
}).data("kendoGrid");
$("#grid").kendoTooltip({
filter: "td:nth-child(2)", //this filter selects the second column's cells
position: "right",
content: function(e){
var dataItem = $("#grid").data("kendoGrid").dataItem(e.target.closest("tr"));
var content = dataItem.Text;
return content;
}
}).data("kendoTooltip");
});
</script>
</body>
</html>
So this line is not enough in my case:
var content = dataItem.Text;
because:
1) I could have field1, field2, field3, etc. In this case, we are assuming that the only column enabled to mouseover is the column named "Text".
2) I need not only the value of any cell the user perform the mouseover, but also the column name.
So what I need to show in the tooltip is:
var content = "column name: " + columname + " - Value: " + columnValue;
Where columname is the name taken from any column mouseover and the columnValue the value of that cell.
Thanks

So I am assuming you just want the column header and the value that is that specific cell you are hovering over if I am understanding your question correctly so rather than showing the entire dataItem object i.e.
{ID:1, Text:"Text Value 1"}
You just want:
Text : Text Value 1
Assuming this is what you want then this dojo should help. http://dojo.telerik.com/uleJEbiz
Here is the code just for reference:
function(e){
var grid = $('#grid').data('kendoGrid');
var rowIndex = e.target.closest("tr").index();
var colIndex = e.target.index();
var dataItem = grid.dataItem(e.target.closest("tr"));
var columns = grid.columns.filter(function(col){
return !col.hidden;
});
var content = 'Found on Row::' + rowIndex + ' Column::' + colIndex +
'<br/>' + columns[colIndex].field + '::' + dataItem[columns[colIndex].field];
return content;
}
All I have done is looked at the problem as a grid we know what row we are looking for but not necessarily the column we are after as we may have hidden columns, so we can't just look at a specific index of the dataItem to pull that item as it may be incorrect. e.g. if you have three properties but the middle one is hidden then you will end up pulling an incorrect value.
So if get the visible column headers only then we can reference the property by the field name.
I have obviously changed the content string to show you the row and column position that we have hit within the grid.

Related

How to display exact value from drop down?

I have configured my select via select2 and things works quite well.
I have used templateResult with formatState approach to add the icon to my dropdown options.
$(".js-country-list").select2({
templateResult: formatState
});
that however does not change anything to selected value (see image below).
How can I make sure that selected value (in my case EUR) would be displayed exactly same as option: Euro (EUR)?
Thanks.
The templateSelection method described at https://select2.org/selections can be used to achieve this, it can be passed the same function used by templateResult.
$(".js-country-list").select2({
templateResult: formatState,
templateSelection: formatState
});
Example listing countries and their flags (not currencies) is incorporated below.
// Template function which adds CSS flag and displays country name
function flagTemplate(country){
return $("<span class='flag-icon flag-icon-" + country.id + " '></span><span class='flag-text'>" + country.text + "</span>");
}
// Generate correct URL based on entered search term
function generateUrl(params){
if(params.term){
return "https://restcountries.com/v3.1/name/" + params.term;
} else {
return "https://restcountries.com/v3.1/all";
}
}
// Initialise select2 using flagTemplate function for both result and selection
$('#countrySelect').select2({
// Set template for results and selection
templateResult: flagTemplate,
templateSelection: flagTemplate,
// Set placeholder text
placeholder: 'Select country...',
// Load country list from https://restcountries.com
ajax: {
url: generateUrl,
cache: 250,
dataType: "json",
processResults: function(data) {
return {
results: data
.map(x => ({id: x.cca2.toLowerCase(), text: x.name.common}))
.sort((a, b) => ('' + a.text).localeCompare(b.text))
};
}
}
});
#countrySelect {
width: 300px;
}
.flag-text {
margin-left: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/js/select2.min.js"></script>
<!-- Load flags using library https://github.com/lipis/flag-icons -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/4.1.5/css/flag-icons.min.css" rel="stylesheet"/>
<select id="countrySelect"><option></option></select>

How to set columns dynamically in Kendo template

How to set columns dynamically in Kendo template for kendo grid.In my kendo grid,columns are subject to change dynamically based on user preference.How to dynamically create Kendo Template?I am using Kendo JavaScript,I can switch to Kendo MVC if same thing i can achieve there.Is there any other approach to achieve this?
<script id="rowTemplate" type="text/x-kendo-template">
<tr class="k-master-row">
<td>
<div>#=column1#</div>
</td>
<td><span class="mydesign" title="column2#"</span></td>
<td>#column3#</td>
<td>#=column4#</td>
</tr>
</script>
Edit : In Kendo grid, we are dynamically setting the columns. Now issue is how do we set the dynamic width for content table and the header table. If it exceeds the max width how do we enable the horizontal scroll bar. Is there any approach to achieve this?
I'm not using kendo for MVC but I can still explain how to do this using regular kendo functions.
Basically, you can create a new kendo template instance by passing an html string to kendo.template. Then you can assign the new template instance to the grid's rowTemplate (or altRowTemplate) then call dataSource.read() to force a grid refresh.
You can generate your own html string or update an existing template in your page then use the jquery's html() to convert it into a string.
Ex:
var htmlTemplate = '';
if (userPreferences.likeRed) {
htmlTemplate ='<tr class="k-master-row"><td style="background-color:red">#column1#</td></tr>'
} else {
htmlTemplate ='<tr class="k-master-row"><td style="background-color:green">#column1#</td></tr>'
}
$("#grid").data("kendoGrid").rowTemplate = kendo.template(htmlTemplate);
$("#grid").data("kendoGrid").dataSource.read();
In order to format Kendo Grid column value with conditionally chosen action you can use one of the suitable examples below. For more information: How Do I Have Conditional Logic in a Column Client Template?
Here are some of the usage samples below. You can easily generate different templates with the help of this approach.
UI for Javascript:
{
field: "EmployeeName", type: "string", width: "55px", title: "Employee Name",
template: "#= GetEditTemplate(data) #"
}
UI for MVC:
...
columns.Bound(t => t.EmployeeName)
.Title("Status Name")
.Template(#<text></text>)
.ClientTemplate("#= GetEditTemplate(data)#")
.Width("55px");
...
Example I: In this example, Model is passed to the Javascript method by using "data" property and the model property is used in the "if" condition.
<script>
//Change the color of the cell value according to the given condition
function GetEditTemplate(data) {
var html;
if (data.StatusID == 1) {
html = kendo.format(
//"<a class=\"k-button\" href='" + '#Url.Action("Edit1", "Controller")' + "/{0}" + " '>Edit</a> ",
"<span class='text-success'>" +
data.EmployeeName
+ "</span>"
);
}
else {
html = kendo.format(
//"<a class=\"k-button\" href='" + '#Url.Action("Edit2", "Controller")' + "/{0}" + " '>Edit</a> ",
"<span class='text-danger'>Cancel</span>"
);
}
return html;
}
</script>
Example II:
<script>
function Getvalue(value) {
// console.log(value);
if (value && value != null && value.indexOf("A") == 0)
return "<b style='color:red'>" + value + "</b>";
else
return "";
}
$(document).ready(function () {
$("#grid").kendoGrid({
dataSource: localDataSource,
columns: [
{
field: "FirstName",
title: "First Name", template: '#=Getvalue(FirstName)#'
}
],
});
});
</script>
Hope this helps...
This will work in ASP.NET MVC/Razor, if you prepare a collection of the dynamic columns definitions in advance, then put them in the view model for the cshtml. Then loop through the collection and insert the field name that will match the datasource, header title, desired width, etc...
$("#grid-quick").kendoGrid({
pageable: {
pageSizes: [10, 20, 50, 100]
},
sortable: { mode: "multiple" },
columns: [
#{
foreach (var col in Model.Columns)
{
#:{ field: "#col.Name.Replace(".","_")", width: "#col.Width" + "px" },
}
}
],
filterable: false,
dataSource: {
serverPaging: true,
serverSorting: true,
pageSize: 20,
type: 'aspnetmvc-ajax',
schema: {
data: "Data",
total: "Total",
model: {
fields: {
#{
foreach (var col in Model.Columns)
{
#: "#col.Name.Replace(".","_")" : { type: "string" },
}
}
}
}
},
transport: {
read: {
url: oVariables.baseURL + "Query/DynamicResults",
dataType: "json",
type: "post"
}
}
}
});

Ext.Ajax.request not working

![
this is the project structure I am using. On adding a local URL like this below code is not working. url:'data/showStudentInfo.html']3I am using Ext Js version 4.1.1
In my application , I am having a grid, which uses a store.
On clicking "click me" button I want to redirect to the server, for test purpose I am using a basic google url,
But the class Ext.Ajax.Request is not working I think
Please help , as I am new to Ext js, I am not aware of the mistake I am making.
I am trying this in notepad++, as well as in eclipse ide (indigo version).
both with same output, Ext.Ajax.Request part not working.
It will of great help if anyone have suggestion as if I want to send
Thanking in advance
Below is my html and js file
practiseCellEditEx.js
Ext.require([
'Ext.data.*',
'Ext.Ajax.',
'Ext.grid.*'
]);
function getRandomDate() {
var from = new Date(1900, 0, 1).getTime();
var to = new Date().getTime();
var date = new Date(from + Math.random() * (to - from));
return Ext.Date.clearTime(date);
}
function createFakeData(count) {
var firstNames = ['Ed', 'Tommy', 'Aaron', 'Abe'];
var lastNames = ['Spencer', 'Maintz', 'Conran', 'Elias'];
var data = [];
for (var i = 0; i < count ; i++) {
var dob = getRandomDate();
var firstNameId = Math.floor(Math.random() * firstNames.length);
var lastNameId = Math.floor(Math.random() * lastNames.length);
var name = Ext.String.format("{0} {1}", firstNames[firstNameId], lastNames[lastNameId]);
data.push([name, dob]);
}
return data;
}
Ext.onReady(function(){
Ext.define('Person',{
extend: 'Ext.data.Model',
fields: ['Name', 'dob']
});
var store = Ext.create('Ext.data.Store', {
model: 'Person',
autoLoad: true,
proxy: {
type: 'memory',
data: createFakeData(10),
reader: {type: 'array'}
},
sorters: [{
direction:'ASC'
}]
});
Ext.create('Ext.grid.Panel', {
store: store,
plugins: [
Ext.create('Ext.grid.plugin.CellEditing', {
clicksToEdit : 1
})
],
columns: [
{
text: "Name",
width:120,
dataIndex: 'Name',
editor : {
xtype: 'textfield',
allowBlank:false
}
},
{
text: "DOB",
width: 120,
dataIndex: 'dob',
renderer: Ext.util.Format.dateRenderer('M d, Y'),
editor: {
xtype: 'datefield',
format: 'M d, Y',
minValue: '01/01/1900',
maxValue: new Date()
}
},
{
xtype: 'actioncolumn',
width: 30,
sortable: false,
menuDisabled: true,
items: [{
icon: 'http://etf-prod-projects-1415177589.us-east-1.elb.amazonaws.com/trac/docasu/export/2/trunk/client/extjs/shared/icons/fam/delete.gif',
handler: function(grid, rowIndex, colIndex) {
store.removeAt(rowIndex);
}
}]
}
],
renderTo:'example-grid',
width: 280,
height: 280
});
Ext.create('Ext.Button', {
text: 'Click me',
// renderTo: Ext.getBody(),
renderTo:'myBtn',
handler: getName
});
function getName (btn)
{
alert("hello");
var records = store.getAt(1);
alert('the name at index 1 is:'+records.get('Name'));
Ext.Ajax.request({
url : 'https://www.google.co.in/'
});
};
/*
function buttonClicked() {
Ext.MessageBox.confirm( 'Delete this part ? :' );
}*/
});
practiseCellEditEx.html
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>ExtJS Samples</title>
<link rel="stylesheet" type="text/css" href="../resources/css/ext-all.css" />
<script type="text/javascript" src="../adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="../ext-all.js"></script>
<script type="text/javascript" src="practiseCellEditEx.js"></script>
</head>
<body>
<h2> <b>Helllo , today's Date is 02.12.2015 </b></h2>
<div id="example-grid"></div>
<!--<button id="myBtn"></button>-->
<div id="myBtn"></div>
</body>
</html>
The problems seems to be simply the request going to google.com. In my browser it is blocked because it is a cross-origin request (an ajax request to another domain), see also here for further information: https://en.wikipedia.org/wiki/Same-origin_policy.
The same code with a request to a local URL works fine.

Table not building

So as I'm not knowledgeable about jQuery and JavaScript I'm following the simpler method of using an array to build a table with Tablesorter. However, this is not working at all. In fact, even if I use the example provided (here: http://mottie.github.io/tablesorter/docs/example-widget-build-table.html) there is no result just a blank webpage. Here's my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Testing Tablesorter (fork)</title>
<!-- load tableSorter theme -->
<link href="./includes/tablesorter-master/css/theme.default.css" rel="stylesheet">
<!-- load jQuery and tableSorter scripts -->
<script type="text/javascript" src="./includes/jquery-2.1.0.js"></script>
<!-- <script src="http://code.jquery.com/jquery-1.11.0.js"></script> -->
<script type="text/javascript" src="./includes/tablesorter-master/js/jquery.tablesorter.js"></script>
<!-- load tableSorter widgets -->
<script type="text/javascript" src="./includes/tablesorter-master/js/jquery.tablesorter.widgets.js"></script>
<script type="text/javascript">
$(document).ready(function(){
// Call the PHP script that grabs all data from DB
$.getJSON('./get_data.php',function(data){
//alert(data.length);
var dataArr = new Array();
for (x = 0; x < data.length; x++)
{
dataArr[x] = data[x];
//console.log(dataArr[$x]);
}
applyTable(dataArr);
});
});
function applyTable(arrayIn)
{
//alert(arrayIn[0]);
$('#topdiv').tablesorter({
theme : 'default',
//widgets : ['zebra','columns'],
debug : true,
widgetOptions : {
build_source : arrayIn,
build_headers : {
rows : 1,
classes : [],
text : [],
widths : [ '15%', '15%', '30%', '15%', '40%', '30%', '30%', '30%', '30%', '30%' ]
}
}
});
$("#topdiv").trigger("updateAll");
}
</script>
</head>
<body>
<div id="topdiv"></div>
</body>
</html>
Any ideas? Mottie, where are you.
EDIT: Chrome reports no JavsScript errors. Though the console (since I specified "debug: true") gives:
stopping initialization! No table, thead, tbody or tablesorter has already been initialized
I also know that the PHP script is working fine.
EDIT, PHP CODE (excerpt):
$headersArr = array('ID', 'Col 2', 'Col 3',
'Col 4', 'Col 5', 'Col 6',
'Col 7', 'Col 8', 'Col 9', 'Col 10');
$allArr = array();
array_push($allArr, $headersArr);
while($row = mysql_fetch_object($rs))
{
$newRow = array($row->id, $row->col_B, $row->col_C,
$row->col_D, $row->col_E,
$row->col_F, $row->col_G,
$row->col_H, $row->col_I,
$row->col_J);
array_push($allArr, $newRow);
}
echo json_encode($jobsArr);
The following image is the JavaScript output in the Chrome console (I have not updated the code above to keep it from getting to big, but I simply repacked the array passed to applyTable() and outputted both arrays to the console). Which one of these arrays should be for use with Tablesorter?
From looking at the code, it looks like the array is just one long array.
dataArr = [ 'r0c0', 'r0c1', 'r0c2', 'r1c0', 'r1c1', 'r1c2', ... ];
It needs to be an array of row arrays:
dataArr = [
['r0c0', 'r0c1', 'r0c2'],
['r1c0', 'r1c1', 'r1c2'],
...
];
so make two loops (demo):
$(function () {
// Declare the array holding the data
var dataArr = [];
// Call the PHP script that grabs all data from DB
$.getJSON('./get_data.php', function (data) {
var i, j, row,
// you need to know how many columns
columns = 3,
// calculate how many rows
rows = Math.ceil(data.length / columns);
for (i = 0; i < rows; i++) {
// clear row array
row = [];
for (j = 0; j < columns; j++) {
row.push(data[i * columns + j]);
}
dataArr.push(row);
}
applyTable(dataArr);
});
});
function applyTable(arrayIn) {
$('#topdiv').tablesorter({
theme: 'default',
//widgets : ['zebra','columns'],
widgetOptions: {
build_source: arrayIn,
build_headers: {
rows: 1,
widths: ['33%', '33%', '33%']
}
}
});
}
And don't trigger an "updateAll" because the table was just built.
The error you mentioned is still showing up, it looks like an bug, but it's just an unintentional message, nothing else.
The table was not building due to missing the line in the HTML header:
<script type="text/javascript" src="./includes/tablesorter-master/js/widgets/widget-build-table.js"></script>
The PHP script is absolutely fine. The only JavaScript req'd is:
$(document).ready(function(){
$.getJSON('./get_data.php',function(data){
applyTable(data);
});
});
function applyTable(arrayIn){
$('#topdiv').tablesorter({
theme: 'default',
//widgets : ['zebra','columns'],
debug: true,
widgetOptions: {
build_source: arrayIn,
build_headers: {
rows: 1
}
}
});

Hyperlinks in Dojo Tree

There is an example tree in the dojo campus with hyperlinks. They are not clickable. Does anyone have a dojo implementation with clickable links? Have you been able to determine which node/link was clicked? I am looking for sample code that does this.
Here is the sample code from dojo campus. How do I make these links clickable and how do I implement node selection from click of image?
Thanks.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html dir="ltr">
<head>
<style type="text/css">
body, html { font-family:helvetica,arial,sans-serif; font-size:90%; }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojo/dojo.xd.js"
djConfig="parseOnLoad: true">
</script>
<script type="text/javascript">
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dijit.Tree");
var rawdata = [{
label: 'Something <b>important</b>',
id: '1',
children: [{
label: 'Life',
id: '1.1'
},
{
label: 'Liberty',
id: '1.2'
}]
},
{
label: 'Some links (note: the link is <b>not</b> clickable)',
id: '2',
children: [{
id: '2.1',
label: 'Dojo Toolkit'
},
{
id: '2.2',
label: '<img src="http://dojofoundation.org/media/img/dojo.logo.png" alt="greatest ever" height="32px" />'
},
{
id: '2.3',
label: 'my blog'
}]
}];
function prepare() {
var store = new dojo.data.ItemFileReadStore({
data: {
identifier: 'id',
label: 'label',
items: rawdata
}
});
var treeModel = new dijit.tree.ForestStoreModel({
store: store
});
var treeControl = new dijit.Tree({
model: treeModel,
showRoot: false,
_createTreeNode: function(
/*Object*/
args) {
var tnode = new dijit._TreeNode(args);
tnode.labelNode.innerHTML = args.label;
return tnode;
}
},
"treeOne");
}
dojo.addOnLoad(prepare);
</script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dijit/themes/claro/claro.css"
/>
</head>
<body class=" claro ">
<div id="treeOne">
</div>
<!-- NOTE: the following script tag is not intended for usage in real
world!! it is part of the CodeGlass and you should just remove it when
you use the code -->
<script type="text/javascript">
dojo.addOnLoad(function() {
if (document.pub) {
document.pub();
}
});
</script>
</body>
</html>
You can do a connect to the onClick event on the Tree. When creating your Tree, add an extra onClick parameter to your constructor, pointing to a function with the following signature:
function myOnClickHandler(item, tree, evt){
//item is the node's DataStore item
//I forgot if tree is the whole tree or just the currtent node
//evt is the usual event object, with things like mouse position, etc...
console.log('clicked a tree');
}
var treeControl = new dijit.Tree({
model: treeModel,
showRoot: false,
_createTreeNode: function( /*Object*/ args) {
var tnode = new dijit._TreeNode(args);
tnode.labelNode.innerHTML = args.label;
return tnode;
},
onClick: myOnclickHandler // THIS LINE //
},
"treeOne");

Resources