So, I'm trying to modify an already existing html file (uses embedded javascript) and change the way it outputs table data. The data that is being inputted into the table is being pulled from another program which stores this one value I want to change as a decimal value. Scouring through the code, I found the section that actually handles what data will be displayed to the table, and it as follows.
var bodyDefine =
[
//{ text: rankingText, width: "5%", align: "center", effect: deadYatsuEffect },
{ text: "{name}", width: "10%" },
{ text: "{Job}", width: "8%", align: "left" },
{ text: "{encdps}", width: "20%", align: "right" },
//{ text: "{damage%}", width: "5%", align: "right" },
//{ text: "{enchps}", width: "16%", align: "right" },
//{ text: "{healed%}", width: "5%", align: "right" },
//{ text: "{tohit}%", width: "16%", align: "right" },
//{ text: "{crithit%}", width: "14%", align: "right" },
];
Edit:
The current output is as follows(example):
Name Job DPS
|John Smith NIN 12653.25 |
|Adam Cook SAM 14577.32 |
But the intended output I want is without the decimal values under DPS.
Name Job DPS
|John Smith NIN 12653 |
|Adam Cook SAM 14577 |
This file was retrieved from https://github.com/hibiyasleep/OverlayPlugin/releases/tag/0.3.4.0 and is used with the program Advanced Combat Tracker with the FFXIV_ACT Plugin. The file below is located in the following directory OverlayPlugin-0.3.4.0-x64-full/resources/miniparse.html
The entire code:
<html>
<head>
<meta charset="utf-8" />
<title></title>
<!--STYLE SECTION REMOVED-->
<script>
//
// プラグイン側から以下のような ActXiv オブジェクトとしてデータが提供される
//
// var ActXiv = {
// "Encounter": {...},
// "Combatant": {
// "PlayerName1": {...},
// "PlayerName2": {...},
// ...
// }
// };
//
// データの更新は 1 秒毎。
//
// プラグインから onOverlayDataUpdate イベントが発行されるので、それを受信することもできる
// イベントハンドラの第一引数の detail プロパティ内に上記のオブジェクトが入る
//
//
// 表示設定 (2)
//
// エンカウント情報の定義
var encounterDefine = "{title} / Time: {duration} / DPS: {ENCDPS}";
// 上記のエンカウント情報を HTML として扱うなら true
var useHTMLEncounterDefine = false;
// ヘッダの定義
var headerDefine =
[
//{ text: "#", width: "5%", align: "center" },
{ text: "Name", width: "10%", align: "left" },
{ text: "Job", width: "8%", align: "left" },
{ text: "DPS", width: "20%", align: "right"},
//{ text: "HPS (%)", width: "18%", align: "center", span: 2 },
//{ text: "Acc.(%)", width: "16%", align: "right" },
//{ text: "Crt.(%)", width: "14%", align: "right" },
];
// 表示するデータの定義
var bodyDefine =
[
//{ text: rankingText, width: "5%", align: "center", effect: deadYatsuEffect },
{ text: "{name}", width: "10%" },
{ text: "{Job}", width: "8%", align: "left" },
{ text: "{encdps}", width: "20%", align: "right" },
//{ text: "{damage%}", width: "5%", align: "right" },
//{ text: "{enchps}", width: "16%", align: "right" },
//{ text: "{healed%}", width: "5%", align: "right" },
//{ text: "{tohit}%", width: "16%", align: "right" },
//{ text: "{crithit%}", width: "14%", align: "right" },
];
// 順位を表示する(text に関数を指定する例)
// 引数:
// combatant : キャラクターのデータ。combatant["..."]でデータを取得できる。
// index : キャラクターの並び順。一番上は 0 で、その後は 1 ずつ増える。
// 戻り値:
// 表示するテキスト。
// ACT のタグは展開されないので、展開したい場合は parseActFormat 関数を使用してください。
function rankingText(combatant, index) {
// 1 から始まる番号を返す
return (index + 1).toString();
}
// 死亡奴を赤くする(effect の例)
// 引数:
// cell : セルの DOM 要素
// combatant : キャラクターのデータ。combatant["..."]でデータを取得できる。
// index: キャラクターの並び順。一番上は 0 で、その後は 1 ずつ増える。
// 戻り値: なし
function deadYatsuEffect(cell, combatant, index) {
// デス数を整数値に変換
var deaths = parseInt(combatant["deaths"]);
// デス数が 0 よりも大きいなら
if (deaths > 0) {
// 赤くする
cell.style.color = "#FFA0A0";
cell.style.textShadow = "-1px 0 3px #802020, 0 1px 3px #802020, 1px 0 3px #802020, 0 -1px 3px #802020";
}
}
//
// 以下表示用スクリプト
//
// onOverlayStateUpdate イベントを購読
document.addEventListener("onOverlayStateUpdate", function (e) {
if (!e.detail.isLocked) {
displayResizeHandle();
} else {
hideResizeHandle();
}
});
function displayResizeHandle() {
document.documentElement.classList.add("resizeHandle");
}
function hideResizeHandle() {
document.documentElement.classList.remove("resizeHandle");
}
// onOverlayDataUpdate イベントを購読
document.addEventListener("onOverlayDataUpdate", function (e) {
update(e.detail);
});
// 表示要素の更新
function update(data) {
updateEncounter(data);
if (document.getElementById("combatantTableHeader") == null) {
updateCombatantListHeader();
}
updateCombatantList(data);
}
// エンカウント情報を更新する
function updateEncounter(data) {
// 要素取得
var encounterElem = document.getElementById('encounter');
// テキスト取得
var elementText;
if (typeof encounterDefine === 'function') {
elementText = encounterDefine(data.Encounter);
if (typeof elementText !== 'string') {
console.log("updateEncounter: 'encounterDefine' is declared as function but not returns a value as string.");
return;
}
} else if (typeof encounterDefine === 'string') {
elementText = parseActFormat(encounterDefine, data.Encounter);
} else {
console.log("updateEncounter: 'encounterDefine' should be string or function that returns string.");
return;
}
// テキスト設定
if (!useHTMLEncounterDefine) {
encounterElem.innerText = parseActFormat(elementText, data.Encounter);
} else {
encounterElem.innerHTML = parseActFormat(elementText, data.Encounter);
}
}
// ヘッダを更新する
function updateCombatantListHeader() {
var table = document.getElementById('combatantTable');
var tableHeader = document.createElement("thead");
tableHeader.id = "combatantTableHeader";
var headerRow = tableHeader.insertRow();
for (var i = 0; i < headerDefine.length; i++) {
var cell = document.createElement("th");
// テキスト設定
if (typeof headerDefine[i].text !== 'undefined') {
cell.innerText = headerDefine[i].text;
} else if (typeof headerDefine[i].html !== 'undefined') {
cell.innerHTML = headerDefine[i].html;
}
// 幅設定
cell.style.width = headerDefine[i].width;
cell.style.maxWidth = headerDefine[i].width;
// 横結合数設定
if (typeof headerDefine[i].span !== 'undefined') {
cell.colSpan = headerDefine[i].span;
}
// 行揃え設定
if (typeof headerDefine[i].align !== 'undefined') {
cell.style["textAlign"] = headerDefine[i].align;
}
headerRow.appendChild(cell);
}
table.tHead = tableHeader;
}
// プレイヤーリストを更新する
function updateCombatantList(data) {
// 要素取得&作成
var table = document.getElementById('combatantTable');
var oldTableBody = table.tBodies.namedItem('combatantTableBody');
var newTableBody = document.createElement("tbody");
newTableBody.id = "combatantTableBody";
// tbody の内容を作成
var combatantIndex = 0;
for (var combatantName in data.Combatant) {
var combatant = data.Combatant[combatantName];
var tableRow = newTableBody.insertRow(newTableBody.rows.length);
for (var i = 0; i < bodyDefine.length; i++)
{
var cell = tableRow.insertCell(i);
// テキスト設定
if (typeof bodyDefine[i].text !== 'undefined') {
var cellText;
if (typeof bodyDefine[i].text === 'function') {
cellText = bodyDefine[i].text(combatant, combatantIndex);
} else {
cellText = parseActFormat(bodyDefine[i].text, combatant);
}
cell.innerText = cellText;
} else if (typeof bodyDefine[i].html !== 'undefined') {
var cellHTML;
if (typeof bodyDefine[i].html === 'function') {
cellHTML = bodyDefine[i].html(combatant, combatantIndex);
} else {
cellHTML = parseActFormat(bodyDefine[i].html, combatant);
}
cell.innerHTML = cellHTML;
}
// 幅設定
cell.style.width = bodyDefine[i].width;
cell.style.maxWidth = bodyDefine[i].width;
// 行構え設定
if (typeof(bodyDefine[i].align) !== 'undefined') {
cell.style.textAlign = bodyDefine[i].align;
}
// エフェクト実行
if (typeof bodyDefine[i].effect === 'function') {
bodyDefine[i].effect(cell, combatant, combatantIndex);
}
}
combatantIndex++;
}
// tbody が既に存在していたら置換、そうでないならテーブルに追加
if (oldTableBody != void(0)) {
table.replaceChild(newTableBody, oldTableBody);
}
else {
table.appendChild(newTableBody);
}
}
// Miniparse フォーマット文字列を解析し、表示文字列を取得する
function parseActFormat(str, dictionary)
{
var result = "";
var currentIndex = 0;
do {
var openBraceIndex = str.indexOf('{', currentIndex);
if (openBraceIndex < 0) {
result += str.slice(currentIndex);
break;
}
else {
result += str.slice(currentIndex, openBraceIndex);
var closeBraceIndex = str.indexOf('}', openBraceIndex);
if (closeBraceIndex < 0) {
// parse error!
console.log("parseActFormat: Parse error: missing close-brace for " + openBraceIndex.toString() + ".");
return "ERROR";
}
else {
var tag = str.slice(openBraceIndex + 1, closeBraceIndex);
if (typeof dictionary[tag] !== 'undefined') {
result += dictionary[tag];
} else {
console.log("parseActFormat: Unknown tag: " + tag);
result += "ERROR";
}
currentIndex = closeBraceIndex + 1;
}
}
} while (currentIndex < str.length);
return result;
}
</script>
</head>
<body>
<div id="encounter">
No data to show.
<!-- ここにエンカウント情報が入る -->
</div>
<table id="combatantTable">
<!-- ここにヘッダが入る -->
<!-- ここに各キャラの情報が入る -->
</table>
</body>
</html>
The code you provided doesn't include any data, just the rendering algorithm. Without knowing what the data looks like, I can only guess based on what I can assume from the code. I can read the comments tho.
function parseActFormat(str, dictionary)
{
var result = "";
var currentIndex = 0;
do {
var openBraceIndex = str.indexOf('{', currentIndex);
if (openBraceIndex < 0) {
result += str.slice(currentIndex);
break;
}
else {
result += str.slice(currentIndex, openBraceIndex);
var closeBraceIndex = str.indexOf('}', openBraceIndex);
if (closeBraceIndex < 0) {
// parse error!
(...)
Just scanning this, it looks like a naive templating engine, for replacing I guess that part text: "{encdps}"
...
Also
var cell = tableRow.insertCell(i);
// テキスト設定
if (typeof bodyDefine[i].text !== 'undefined') {
var cellText;
if (typeof bodyDefine[i].text === 'function') {
cellText = bodyDefine[i].text(combatant, combatantIndex);
} else {
cellText = parseActFormat(bodyDefine[i].text, combatant);
}
cell.innerText = cellText;
From that part it seems that you can define the text as a function instead of a string, so try this:
{ text: function(combatant){ return Number(String(combatant.encdps)).toFixed(0); }, width: "20%", align: "right" },
Related
The sorting function will no longer work on column that is using itemTemplate and headerTemplate.
You can see a fiddle from here.
As you can see, in the column "Client ID", the sorting works really well. But on column "Client Name", the sorting doesn't work as I am using itemTemplate and headerTemplate for customization.
Any workaround is really appreciated.
Here's the code:
$("#jsGrid").jsGrid({
width: "100%",
sorting: true,
paging: true,
data: [{
ClientId: 1,
Client: "Aaaa Joseph"
},
{
ClientId: 2,
Client: "Zzzz Brad"
},
{
ClientId: 3,
Client: "Mr Nice Guy"
}
],
fields: [{
width: 80,
name: "ClientId",
type: "text",
title: "Client ID"
},
{
width: 80,
itemTemplate: function(value, item) {
return "<div>" + item.Client + "</div>";
},
headerTemplate: function() {
return "<th class='jsgrid-header-cell'>Client Name</th>";
}
},
]
});
In jsgrid name is a property of data item associated with the column. And on header click this _sortData function will call in jsgrid.js for sorting data. And this name config will use here. So for this you have to provide this config other it will blank and no data sorting on header click.
Please search this below function in jsgrid.js
_sortData: function() {
var sortFactor = this._sortFactor(),
sortField = this._sortField;
if (sortField) {
this.data.sort(function(item1, item2) {
return sortFactor * sortField.sortingFunc(item1[sortField.name], item2[sortField.name]);
});
}
},
In above code sortField.name as column config and it is must mandatory.
DEMO
$("#jsGrid").jsGrid({
width: "100%",
sorting: true,
paging: true,
data: [
{ ClientId : 1, Client: "Aaaa Joseph"},
{ ClientId : 2, Client: "Zzzz Brad"},
{ ClientId : 3, Client: "Mr Nice Guy"}
],
fields: [
{
width: 80,
name: "ClientId",
type: "text",
title: "Client ID"
},
{
width: 80,
name:'Client',
itemTemplate: function (value, item) {
return "<div>"+item.Client+"</div>";
},
headerTemplate: function () {
return "<th class='jsgrid-header-cell'>Client Name</th>";
}
},
]
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.css" />
<link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid-theme.min.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.js"></script>
<div id="jsGrid"></div>
Another way you can make manually sorting on header click.
Way to sort JS grid on column after grid load :
onRefreshing: function (args) {
fundCodeList = [];
jsonNumLst = [];
jsonNANLst = [];
if(this._visibleFieldIndex(this._sortField) == -1
|| this._visibleFieldIndex(this._sortField)==1){
$.each(filteredData, function(inx, obj) {
if($.isNumeric(obj.fundCode)){
jsonNumLst.push(obj);
}else{
jsonNANLst.push(obj);
}
});
if(this._sortOrder == undefined || this._sortOrder == 'asc'){
jsonNumLst.sort(sortByNumFCAsc);
jsonNANLst.sort(sortByNANFCAsc);
}else if(this._sortOrder == 'desc'){
jsonNANLst.sort(sortByNANFCDesc);
jsonNumLst.sort(sortByNumFCDesc);
}
if(jsonNumLst.length>0 || jsonNANLst.length>0){
filteredData = [];
if(this._sortOrder == undefined || this._sortOrder == 'asc'){
$.each(jsonNumLst, function(inx, obj) {
filteredData.push(obj);
});
if(filteredData.length == jsonNumLst.length){
$.each(jsonNANLst, function(inx, obj) {
filteredData.push(obj);
});
}
}else if(this._sortOrder == 'desc'){
$.each(jsonNANLst, function(inx, obj) {
filteredData.push(obj);
});
if(filteredData.length == jsonNANLst.length){
$.each(jsonNumLst, function(inx, obj) {
filteredData.push(obj);
});
}
}
}
if((filteredData.length>0) && filteredData.length==(jsonNumLst.length+jsonNANLst.length)){
$("#measureImportGrid3").data("JSGrid").data = filteredData;
//isSortGrid = false;
//saveEffectControlData = $('#saveEffectiveControlGrid').jsGrid('option', 'data');
}
}
}
//Ascending order numeric
function sortByNumFCAsc(x,y) {
return x.fundCode - y.fundCode;
}
//Ascending order nonnumeric
function sortByNANFCAsc(x,y) {
return ((x.fundCode == y.fundCode) ? 0 : ((x.fundCode > y.fundCode) ? 1 : -1 ));
}
//Descending order numeric
function sortByNANFCDesc(x,y) {
return ((x.fundCode == y.fundCode) ? 0 : ((y.fundCode > x.fundCode) ? 1 : -1 ));
}
//Descending order non-numeric
function sortByNumFCDesc(x,y) {
return y.fundCode - x.fundCode;
}
I am trying display data in jQuery datatable but, I am seeing unexpected vertical scrollbar.
Fiddler: https://jsfiddle.net/8f63kmeo/15/
HTML:
<table id="CustomFilterOnTop" class="table table-bordered table-condensed" width="100%"></table>
JS
var Report4Component = (function () {
function Report4Component() {
//contorls
this.customFilterOnTopControl = "CustomFilterOnTop"; //table id
//data table object
this.customFilterOnTopGrid = null;
//variables
this.result = null;
}
Report4Component.prototype.ShowGrid = function () {
var instance = this;
//create the datatable object
instance.customFilterOnTopGrid = $('#' + instance.customFilterOnTopControl).DataTable({
columns: [
{ title: "<input name='SelectOrDeselect' value='1' id='ChkBoxSelectAllOrDeselect' type='checkbox'/>" },
{ data: "Description", title: "Desc" },
{ data: "Status", title: "Status" },
{ data: "Count", title: "Count" }
],
"paging": true,
scrollCollapse: true,
"scrollX": true,
scrollY: "50vh",
deferRender: true,
scroller: true,
dom: '<"top"Bf<"clear">>rt <"bottom"<"Notes">i<"clear">>',
buttons: [
{
text: 'Load All',
action: function (e, dt, node, config) {
instance.ShowData(10000);
}
}
],
columnDefs: [{
orderable: false,
className: 'select-checkbox text-center',
targets: 0,
render: function (data, type, row) {
return '';
}
}],
select: {
style: 'multi',
selector: 'td:first-child',
className: 'selected-row selected'
}
});
};
Report4Component.prototype.ShowData = function (limit) {
if (limit === void 0) { limit = 2; }
var instance = this;
instance.customFilterOnTopGrid.clear(); //latest api function
instance.result = instance.GetData(limit);
instance.customFilterOnTopGrid.rows.add(instance.result.RecordList);
instance.customFilterOnTopGrid.draw();
};
Report4Component.prototype.GetData = function (limit) {
//structure of the response from controller method
var resultObj = {};
resultObj.Total = 0;
resultObj.RecordList = [];
for (var i = 1; i <= limit; i++) {
resultObj.Total += i;
var record = {};
record.Description = "Some test data will be displayed here.This is a test description of record " + i;
record.Status = ["A", "B", "C", "D"][Math.floor(Math.random() * 4)] + 'name text ' + i;
record.Count = i;
resultObj.RecordList.push(record);
}
return resultObj;
};
return Report4Component;
}());
$(function () {
var report4Component = new Report4Component();
report4Component.ShowGrid();
report4Component.ShowData();
});
function StopPropagation(evt) {
if (evt.stopPropagation !== undefined) {
evt.stopPropagation();
}
else {
evt.cancelBubble = true;
}
}
ISSUE:
I am wondering why the vertical scrollbar is appearing and why I am seeing an incorrect count...? Is it because my datatable has rows with multiple lines? As I have already set the scrolly to 50vh, I am expecting all the rows to be displayed.
Note:
The table should support large data too. I have enabled scroller for that purpose as it is required as per the application design. To verify that click on "Load all" button.
Any suggestion / help will be greatly appreciated?
You just need to remove property " scroller: true" it will solve your problem.
For demo please check https://jsfiddle.net/dipakthoke07/8f63kmeo/20/
The following code is used to display a chart. The problem is the "data" is hard coded in. How can I change this so that the chart displays values which are displayed using:
<div id="name"> </div>
<div id="testscore"></div>
The above 2 div's contain dynamic values. I want to display these values in the chart.
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer",
{
// title:{
// text: "Olympic Medals of all Times (till 2012 Olympics)"
// },
animationEnabled: true,
legend: {
cursor:"pointer",
itemclick : function(e) {
if (typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
e.dataSeries.visible = false;
}
else {
e.dataSeries.visible = true;
}
chart.render();
}
},
axisY: {
title: "Time"
},
toolTip: {
shared: true,
content: function(e){
var str = '';
var total = 0 ;
var str3;
var str2 ;
for (var i = 0; i < e.entries.length; i++){
var str1 = "<span style= 'color:"+e.entries[i].dataSeries.color + "'> " + e.entries[i].dataSeries.name + "</span>: <strong>"+ e.entries[i].dataPoint.y + "</strong> <br/>" ;
total = e.entries[i].dataPoint.y + total;
str = str.concat(str1);
}
str2 = "<span style = 'color:DodgerBlue; '><strong>"+e.entries[0].dataPoint.label + "</strong></span><br/>";
str3 = "<span style = 'color:Tomato '>Total: </span><strong>" + total + "</strong><br/>";
return (str2.concat(str)).concat(str3);
}
},
data: [
{
type: "bar",
showInLegend: true,
name: "Black",
color: "#000000",
dataPoints: [
{ y: 0.18, label: "Name"},
{ y: 0.12, label: "Name 1"},
{ y: 0.59, label: "Name 2"},
{ y: 1.15, label: "Name 3"},
]
},
]
});
chart.render();
}
</script>
You can simply call
var data = document.getElementById('name').value;
var data2 = document.getElementById('testscore').value;
If it's a single value, it would work; otherwise, you need to do it this way:
var array = $('#your.id').data('stuff');
Here, "stuff" is nothing but
<div data-stuff="some data" ></div>
Or, create an array by:
var array = new Array();
and finally, store the data into the array.
I have a KendoTreeview with spriteclass. I want to highlight the nodes (root as well as child nodes) with my search term. I have implemented the search functionality. But the issue when i search it is highlighting the term in the nodes but missing the SpriteClass in the nodes after first search. Any idea ?
jsFiddle code
$('#search-term').on('keyup', function () {
$('span.k-in > span.highlight').each(function () {
$(this).parent().text($(this).parent().text());
});
// ignore if no search term
if ($.trim($(this).val()) == '') {
return;
}
var term = this.value.toUpperCase();
var tlen = term.length;
$('#treeview-sprites span.k-in').each(function (index) {
var text = $(this).text();
var html = '';
var q = 0;
while ((p = text.toUpperCase().indexOf(term, q)) >= 0) {
html += text.substring(q, p) + '<span class="highlight">' + text.substr(p, tlen) + '</span>';
q = p + tlen;
}
if (q > 0) {
html += text.substring(q);
$(this).html(html);
$(this).parentsUntil('.k-treeview').filter('.k-item').each(
function (index, element) {
$('#treeview-sprites').data('kendoTreeView').expand($(this));
$(this).data('search-term', term);
});
}
});
$("#treeview-sprites").kendoTreeView({
dataSource: [{
text: "My Documents",
expanded: true,
spriteCssClass: "rootfolder",
items: [{
text: "Kendo UI Project",
expanded: true,
spriteCssClass: "folder",
items: [{
text: "about.html",
spriteCssClass: "html"
}, {
text: "index.html",
spriteCssClass: "html"
}, {
text: "logo.png",
spriteCssClass: "image"
}]
}, {
text: "New Web Site",
expanded: true,
spriteCssClass: "folder",
items: [{
text: "mockup.jpg",
spriteCssClass: "image"
}, {
text: "Research.pdf",
spriteCssClass: "pdf"
}, ]
}, {
text: "Reports",
expanded: true,
spriteCssClass: "folder",
items: [{
text: "February.pdf",
spriteCssClass: "pdf"
}, {
text: "March.pdf",
spriteCssClass: "pdf"
}, {
text: "April.pdf",
spriteCssClass: "pdf"
}]
}]
}]
})
;
Kendo's tree view widget doesn't like it if you muck around in its HTML, so I suggest modifying the data source instead (this will require the encoded option for all items in the DS).
In the keyup handler, you reset the DS whenever you search to clear highlighting, then instead of replacing the element's HTML directly, you set the model's text property:
$('#search-term').on('keyup', function () {
var treeView = $("#treeview-sprites").getKendoTreeView();
treeView.dataSource.data(pristine);
// ignore if no search term
if ($.trim($(this).val()) == '') {
return;
}
var term = this.value.toUpperCase();
var tlen = term.length;
$('#treeview-sprites span.k-in').each(function (index) {
var text = $(this).text();
var html = '';
var q = 0;
while ((p = text.toUpperCase().indexOf(term, q)) >= 0) {
html += text.substring(q, p) + '<span class="highlight">' + text.substr(p, tlen) + '</span>';
q = p + tlen;
}
if (q > 0) {
html += text.substring(q);
var dataItem = treeView.dataItem($(this));
dataItem.set("text", html);
$(this).parentsUntil('.k-treeview').filter('.k-item').each(
function (index, element) {
$('#treeview-sprites').data('kendoTreeView').expand($(this));
$(this).data('search-term', term);
});
}
});
$('#treeview-sprites .k-item').each(function () {
if ($(this).data('search-term') != term) {
$('#treeview-sprites').data('kendoTreeView').collapse($(this));
}
});
});
The tree definition needs the encoded option for this to work:
var pristine = [{
encoded: false,
text: "Kendo UI Project",
expanded: true,
spriteCssClass: "folder",
items: [{
encoded: false,
text: "about.html",
spriteCssClass: "html"
}, {
encoded: false,
text: "index.html",
spriteCssClass: "html"
}, {
encoded: false,
text: "logo.png",
spriteCssClass: "image"
}]
}, {
encoded: false,
text: "New Web Site",
expanded: true,
spriteCssClass: "folder",
items: [{
encoded: false,
text: "mockup.jpg",
spriteCssClass: "image"
}, {
encoded: false,
text: "Research.pdf",
spriteCssClass: "pdf"
}, ]
}, {
encoded: false,
text: "Reports",
expanded: true,
spriteCssClass: "folder",
items: [{
encoded: false,
text: "February.pdf",
spriteCssClass: "pdf"
}, {
encoded: false,
text: "March.pdf",
spriteCssClass: "pdf"
}, {
encoded: false,
text: "April.pdf",
spriteCssClass: "pdf"
}]
}];
$("#treeview-sprites").kendoTreeView({
dataSource: [{
text: "My Documents",
expanded: true,
spriteCssClass: "rootfolder",
items: pristine
}]
});
(demo)
Good job guys, just what I neeeded!
Using your code I did a small tweak (actually added just two lines of jquery filtering), so that now when searching for a keyword, the treeview shows only the branches that contain highlighted texts. Easy peasy! :)
Other branches are hidden if they do not contain the higlighted text. Simple as that.
This means we now have a VisualStudio-like treeview search (see the Visual Studio Solution Explorer Search and Filter: http://goo.gl/qr7yVb).
Here's my code and demo on jsfiddle: http://jsfiddle.net/ComboFusion/d0qespaz/2/
HTML:
<input id="treeViewSearchInput"></input>
<ul id="treeview">
<li data-expanded="true">My Web Site
<ul>
<li data-expanded="true">images
<ul>
<li>logo.png</li>
<li>body-back.png</li>
<li>my-photo.jpg</li>
</ul>
</li>
<li data-expanded="true">resources
<ul>
<li data-expanded="true">pdf
<ul>
<li>brochure.pdf</li>
<li>prices.pdf</li>
</ul>
</li>
<li>zip</li>
</ul>
</li>
<li>about.html</li>
<li>contacts.html</li>
<li>index.html</li>
<li>portfolio.html</li>
</ul>
</li>
<li>Another Root</li>
</ul>
CSS
span.k-in > span.highlight {
background: #7EA700;
color: #ffffff;
border: 1px solid green;
padding: 1px;
}
JAVASCRIPT
function InitSearch(treeViewId, searchInputId) {
var tv = $(treeViewId).data('kendoTreeView');
$(searchInputId).on('keyup', function () {
$(treeViewId + ' li.k-item').show();
$('span.k-in > span.highlight').each(function () {
$(this).parent().text($(this).parent().text());
});
// ignore if no search term
if ($.trim($(this).val()) === '') {
return;
}
var term = this.value.toUpperCase();
var tlen = term.length;
$(treeViewId + ' span.k-in').each(function (index) {
var text = $(this).text();
var html = '';
var q = 0;
var p;
while ((p = text.toUpperCase().indexOf(term, q)) >= 0) {
html += text.substring(q, p) + '<span class="highlight">' + text.substr(p, tlen) + '</span>';
q = p + tlen;
}
if (q > 0) {
html += text.substring(q);
$(this).html(html);
$(this).parentsUntil('.k-treeview').filter('.k-item').each(function (index, element) {
tv.expand($(this));
$(this).data('SearchTerm', term);
});
}
});
$(treeViewId + ' li.k-item:not(:has(".highlight"))').hide();
$(treeViewId + ' li.k-item').expand(".k-item");
});
}
var $tv = $("#treeview").kendoTreeView();
InitSearch("#treeview", "#treeViewSearchInput");
Another tweak from me :)
What I did was change the highlight code in order to preserve anything else that might exist in the node html (such as sprite span for example).
I also implemented it as a TypeScript class wrapper around the TreeView.
If you don't want TypeScript stuff just copy the code out and it should work fine :)
export class SearchableTreeView {
TreeView: kendo.ui.TreeView;
emphasisClass: string;
constructor(treeView: kendo.ui.TreeView) {
this.TreeView = treeView;
this.emphasisClass = "bg-warning";
}
search(term: string): void {
var treeElement: JQuery = this.TreeView.element;
var tv: kendo.ui.TreeView = this.TreeView;
var emphClass = this.emphasisClass;
this.resetHighlights();
// ignore if no search term
if ($.trim(term) === '') { return; }
var term = term.toUpperCase();
var tlen = term.length;
$('span.k-in', treeElement).each(function (index) {
// find all corresponding nodes
var node = $(this);
var htmlContent = node.html();
var text = node.text();
var searchPosition = text.toUpperCase().indexOf(term);
if (searchPosition === -1) {
// continue
return true;
}
var generatedHtml = '<span class="highlight-container">' + text.substr(0, searchPosition) + '<span class="' + emphClass + '">' + text.substr(searchPosition, tlen) + '</span>' + text.substr(searchPosition + tlen) + '</span>';
htmlContent = htmlContent.replace(text, generatedHtml);
node.html(htmlContent);
node.parentsUntil('.k-treeview').filter('.k-item').each(
function (index, element) {
tv.expand($(this));
$(this).data('search-term', term);
}
);
});
$('.k-item', treeElement).each(function () {
if ($(this).data('search-term') != term) {
tv.collapse($(this));
}
});
}
resetHighlights(): void {
this.TreeView.element.find("span.k-in:has('." + this.emphasisClass + "')")
.each(function () {
var node = $(this);
var text = node.text();
$(".highlight-container", node).remove();
node.append(text);
});
}
}
$("#textBox").on("input", function () {
var query = this.value.toLowerCase();
var dataSource = $("#Treeview").data("kendoTreeView").dataSource;
filter(dataSource, query);
});
function filter(dataSource, query) {
var uidData = [];
var data = dataSource instanceof kendo.data.DataSource && dataSource.data();
for (var i = 0; i < data.length; i++) {
var item = data[i];
var text = item.text.toLowerCase();
var isChecked = item.checked;
var itemVisible =
query === true
|| query === ""
|| text.indexOf(query) >= 0;
uidData.push({ UID: item.uid, Visible: itemVisible });
}
if (query != "") {
$.each(uidData, function (index, datavalue) {
if (datavalue.Visible) {
$("li[data-uid='" + datavalue.UID + "']").addClass("highlight");
}
else {
$("li[data-uid='" + datavalue.UID + "']").removeClass("highlight");
}
});
}
else {
$.each(uidData, function (index, datavalue) {
$("li[data-uid='" + datavalue.UID + "']").removeClass("highlight");
});
}
}
CSS :
.highlight {
background:#0fa1ba;
color:white;
}
For Angular 2+ you need to create a pipe for this feature.
import { Pipe, PipeTransform } from '#angular/core';
import { DomSanitizer } from '#angular/platform-browser';
import { NGXLogger } from 'ngx-logger';
#Pipe({
name: 'highlight'
})
export class TypeaheadHighlight implements PipeTransform {
constructor(private readonly _sanitizer: DomSanitizer, private readonly logger: NGXLogger) { }
transform(matchItem: any, query: any): string {
let matchedItem: any;
if (matchItem) {
matchedItem = matchItem.toString();
}
if (this.containsHtml(matchedItem)) {
this.logger.warn('Unsafe use of typeahead please use ngSanitize');
}
matchedItem = query ? ('' + matchedItem).replace(new RegExp(this.escapeRegexp(query), 'gi'), '<strong>$&</strong>') : matchedItem; // Replaces the capture string with a the same string inside of a "strong" tag
if (!this._sanitizer) {
matchedItem = this._sanitizer.bypassSecurityTrustHtml(matchedItem);
}
return matchedItem;
}
escapeRegexp = (queryToEscape) => queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
containsHtml = (matchItem) => /<.*>/g.test(matchItem);
}
Use of this pipe in html template....
<input name="searchTerm" type="text" [(ngModel)]="searchTerm" (keyup)='onkeyup(searchTerm)'
/>
</div>
<div style="height: 70vh;overflow: auto">
<kendo-treeview style="margin-top: 50px" id="availableColumns" [nodes]="availableColumns"
textField="displayName" kendoTreeViewExpandable kendoTreeViewFlatDataBinding idField="id"
parentIdField="parentId">
<ng-template kendoTreeViewNodeTemplate let-dataItem>
<span [tooltip]="dataItem.columnDescription"
[innerHtml]="dataItem.displayName | highlight:searchTerm "></span>
</ng-template>
</kendo-treeview>
</div>
Back again with another ExtJS query. I have a grid with a SummaryGroup feature that is toggle-able (enabled/disabled) from a tool button on the panel header. Enabling once displays it properly, disable then try enable the feature. The grouping happens but the Summery totals of the groups doesn't come back again?
JS fiddle here: http://jsfiddle.net/hD4C4/1/
In the fiddle it will show the group totals then if you disable and re-enable again they disappear?
Here is a picture of pressing the button once:
Here is the same grid after disabling it then re-enabling it again:
Below is the toggle code on the panel header tool button:
xtype: 'tool',
type: 'expand',
tooltip: 'Enable grouping',
handler: function(e, target, panelHeader, tool){
var serviceGridView = Ext.getCmp('serviceOverview').getView('groupingFeature'),
gridFeature = serviceGridView.getFeature('serviceOverviewGroupingFeature');
if (tool.type == 'expand') {
gridFeature.enable();
tool.setType('collapse');
tool.setTooltip('Disable grouping');
} else {
gridFeature.disable();
Ext.getCmp('serviceOverview').setLoading(false,false);
Ext.getCmp('serviceOverview').getStore().reload();
tool.setType('expand');
tool.setTooltip('Enable grouping');
}
}
And here is my grid code (with the feature function at the top:
var groupingFeature = Ext.create('Ext.grid.feature.GroupingSummary', {
groupHeaderTpl: Ext.create('Ext.XTemplate',
'',
'{name:this.formatName} ({rows.length})',
{
formatName: function(name) {
return '<span style="color: #3892d3;">' + name.charAt(0).toUpperCase() + name.slice(1) + '</span>';
}
}
),
hideGroupedHeader: false,
startCollapsed: true,
showSummaryRow: true,
id: 'serviceOverviewGroupingFeature'
});
Ext.define('APP.view.core.grids.Serviceoverview', {
extend: 'Ext.grid.Panel',
alias: 'widget.gridportlet',
height: 'auto',
id: 'serviceOverview',
cls: 'productsGrid',
viewConfig: {
loadMask: true
},
features: [groupingFeature, {ftype: 'summary'}],
initComponent: function(){
var store = Ext.create('APP.store.Serviceoverview');
Ext.apply(this, {
height: this.height,
store: store,
stripeRows: true,
columnLines: true,
columns: [{
id :'service-product',
text : 'Product',
flex: 1,
sortable : true,
dataIndex: 'PACKAGE',
summaryType: function(records) {
if (typeof records[0] !== 'undefined') {
var myGroupName = records[0].get('LISTING');
if (this.isStore) {
return '<span style="font-weight: bold;">Total of all</span>';
}
return '<span style="font-weight: bold;">'+myGroupName.charAt(0).toUpperCase() + myGroupName.slice(1)+' Totals</span>';
//return '<span style="font-weight: bold;">Totals</span>';
}
},
renderer: function(value, metaData ,record) {
return value;
}
},{
id :'service-listing',
text : 'Listing',
flex: 1,
sortable : true,
dataIndex: 'LISTING',
renderer: function(value, metaData ,record){
return value.charAt(0).toUpperCase() + value.slice(1);
}
},{
id :'service-total',
text : 'Running Total',
flex: 1,
sortable : true,
dataIndex: 'TOTAL',
summaryType: function(values) {
var total=0.0;
Ext.Array.forEach(values, function (record){
if (record.data.TOTAL !== null) {
total += parseFloat(record.data.TOTAL);
}
});
return '<span style="font-weight: bold;">£' + numeral(total.toFixed(2)).format('0,0.00') + '</span>';
},
renderer: function(value, metaData ,record){
if (value == null) {
return '£0.00';
}
return '£' + numeral(value).format('0,0.00');
}
},{
id :'service-total-paid',
text : 'Total Paid',
flex: 1,
sortable : true,
dataIndex: 'TOTAL_PAID',
summaryType: function(values) {
var total=0.0;
Ext.Array.forEach(values, function (record){
if (record.data.TOTAL_PAID !== null) {
total += parseFloat(record.data.TOTAL_PAID);
}
});
return '<span style="font-weight: bold;">£' + numeral(total.toFixed(2)).format('0,0.00') + '</span>';
},
renderer: function(value, metaData ,record){
if (value == null) {
return '£0.00';
}
return '£' + numeral(value).format('0,0.00');
}
},{
id :'service-outstanding',
text : 'Outstanding',
flex: 1,
sortable : true,
dataIndex: 'OUTSTANDING',
summaryType: function(values) {
var total=0.0;
Ext.Array.forEach(values, function (record){
if (record.data.OUTSTANDING !== null) {
total += parseFloat(record.data.OUTSTANDING);
}
});
return '<span style="font-weight: bold;">£' + numeral(total.toFixed(2)).format('0,0.00') + '</span>';
},
renderer: function(value, metaData ,record){
if (value == null) {
return '£0.00';
}
return '£' + numeral(value).format('0,0.00');
}
},{
id :'service-properties',
text : 'No. of Clients',
flex: 1,
sortable : true,
dataIndex: 'CLIENTS',
summaryType: function(values) {
var total=0.0;
Ext.Array.forEach(values, function (record){
if (record.data.CLIENTS !== null) {
total += parseFloat(record.data.CLIENTS);
}
});
return '<span style="font-weight: bold;">' + total + '</span>';
}
},{
id :'service-average-total',
text : 'Av. Total',
flex: 1,
sortable : true,
dataIndex: 'AVERAGE_TOTAL',
summaryType: function(values) {
var total=0.0;
Ext.Array.forEach(values, function (record){
if (record.data.AVERAGE_TOTAL !== null) {
total += parseFloat(record.data.AVERAGE_TOTAL);
}
});
return '<span style="font-weight: bold;">£' + numeral(total.toFixed(2)).format('0,0.00') + '</span>';
},
renderer: function(value, metaData ,record){
if (value == null) {
return '£0.00';
}
return '£' + numeral(value).format('0,0.00');
}
},{
id :'service-average-total-paid',
text : 'Av. Total Paid',
flex: 1,
sortable : true,
dataIndex: 'AVERAGE_TOTAL_PAID',
summaryType: function(values) {
var total=0.0;
Ext.Array.forEach(values, function (record){
if (record.data.AVERAGE_TOTAL_PAID !== null) {
total += parseFloat(record.data.AVERAGE_TOTAL_PAID);
}
});
return '<span style="font-weight: bold;">£' + numeral(total.toFixed(2)).format('0,0.00') + '</span>';
},
renderer: function(value, metaData ,record){
if (value == null) {
return '£0.00';
}
return '£' + numeral(value).format('0,0.00');
}
},{
id :'service-average-outstanding',
text : 'Av. Outstanding',
flex: 1,
sortable : true,
dataIndex: 'AVERAGE_OUTSTANDING',
summaryType: function(values) {
var total=0.0;
Ext.Array.forEach(values, function (record){
if (record.data.AVERAGE_OUTSTANDING !== null) {
total += parseFloat(record.data.AVERAGE_OUTSTANDING);
}
});
return '<span style="font-weight: bold;">£' + numeral(total.toFixed(2)).format('0,0.00') + '</span>';
},
renderer: function(value, metaData ,record){
if (value == null) {
return '£0.00';
}
return '£' + numeral(value).format('0,0.00');
}
}]
});
this.callParent(arguments);
}
});
Thank you in advance :)
Nathan
It looks like bug.
I have analyzed code a bit, and I discovered that this issue is caused by generateSummaryData method in feature. In this method you can find this code:
if (hasRemote || store.updating || groupInfo.lastGeneration !== group.generation) {
record = me.populateRecord(group, groupInfo, remoteData);
if (!lockingPartner || (me.view.ownerCt === me.view.ownerCt.ownerLockable.normalGrid)) {
groupInfo.lastGeneration = group.generation;
}
} else {
record = me.getAggregateRecord(group);
}
When grid is firstly rendered first branch is executed for all groups, and after reenabling - second branch. Calling getAggregateRecord instead of populateRecord produces empty summary record. I didn't go any deeper, so for now I can only give you dirty hack to override this (it forces code to enter first branch):
store.updating = true;
feature.enable();
store.updating = false;
JSfiddle: http://jsfiddle.net/P2e7s/6/
After some more digging I've found out that most likely this issue occurs because group.generation is not incremented when populateRecord is called. As a result group.generation always equals to 1, so record is populated only when lastGeneration is empty (first code pass). After re-enabling feature, new groups are created, but they also have generation set to 1.
So I've came up with less dirty hack:
Ext.define('Ext.override.grid.feature.AbstractSummary', {
override: 'Ext.grid.feature.GroupingSummary',
populateRecord: function (group, groupInfo, remoteData) {
++group.generation;
return this.callParent(arguments);
}
});
With that override, you can simply enable feature, and it should work.
JSFiddle: http://jsfiddle.net/P2e7s/9/