Passing data into chart using HTML and JavaScript - javascript

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.

Related

Filter entire table from a specific 3rd-tier-nested JSON Tabulator property

I have a triple-nested JSON object where initially all of the data displays in one Tabulator table. For example, this hospital data is a list of diagnosis codes for each patient visit per each patient's medical record. I want to filter by a diagnosis code and display only those patient medical records/ accounts that contain the diagnosis code and redisplay in the same table. Is this possible to do with Tabulator functions?
Basically, how can I display a list of only those 'medical records > patient accounts > diagnosis codes' that contain the 'D55.0' dx_code. If I where to search by a diagnosis code that is not attached to any account, like A01.00, then nothing would display.
var patient_data = [{
med_rec_num:123,
patient_name:"Mickey Mouse",
phone:"123456789",
age:91,
visit_list: [{
account_num: "A0001",
doctor: "Dr. Pepper",
location: "Cardiology",
diagnosis_list: [{
num: 1,
dx_code: "V95.43XA",
visit_type: "Outpatient",
poa: 'Y'
},
{
num: 2,
dx_code: "V95.00A",
visit_type: "Outpatient",
poa: 'N'
},
{
num: 3,
dx_code: "D55.0",
visit_type: "Outpatient",
poa: 'Y'
}
]
},
{
account_num: "A0002",
doctor: "Dr. Dre",
location: "Radiology",
diagnosis_list: [{
num: 1,
dx_code: "K56.60",
visit_type: "Inpatient",
poa: 'Y'
},
{
num: 2,
dx_code: "Z71.89",
visit_type: "Inpatient",
poa: 'Y'
}
]
}
]
},
{
med_rec_num:456,
patient_name:"Jane Smith",
phone:"987654321",
age:50,
visit_list: [{
account_num: "B0001",
doctor: "Dr. Happy",
location: "Pharmacology",
diagnosis_list: [{
num: 1,
dx_code: "Z71.89",
visit_type: "Inpatient",
poa: 'Y'
},
{
num: 2,
dx_code: "D55.0",
visit_type: "Outpatient",
poa: 'N'
}
]
}
]
}
]
const table = new Tabulator("#example-table", {
data: patient_data,
//height: "311px",
layout: "fitColumns",
resizableColumns: false,
index: "med_rec_num",
columns: [
{formatter: plusIcon, width: 55, hozAlign:"center", tooltip: "Click to expand for Visits info", title:"Visits", headerSort:false, cellClick:function(e, row, formatterParams){
const id = row.getData().med_rec_num;
$(".visitTable" + id + "").toggle();}
},
{title:"Medical Record Num", field:"med_rec_num"},
{title:"Patient Name", field:"patient_name"},
{title:"Phone", field:"phone"},
{title:"Age", field:"age"}
],
rowFormatter: function(row, e) {
//create and style holder elements
var holderEl = document.createElement("div");
var tableEl = document.createElement("div");
const id = row.getData().med_rec_num;
holderEl.style.boxSizing = "border-box";
holderEl.style.padding = "10px 10px 10px 10px";
holderEl.style.borderTop = "1px solid #333";
holderEl.style.borderBotom = "1px solid #333";
holderEl.style.background = "#ddd";
//holderEl.style.display = "none";
holderEl.setAttribute('class', "visitTable" + id + "");
tableEl.style.border = "1px solid #333";
//tableEl.style.display = "none";
tableEl.setAttribute('class', "visitTable" + id + "");
holderEl.appendChild(tableEl);
row.getElement().appendChild(holderEl);
var visitTable = new Tabulator(tableEl, {
layout: "fitColumns",
data: row.getData().visit_list,
index: "account_num",
columns: [
{formatter: plusIcon, width: 55, hozAlign:"center", tooltip: "Click to expand for Dx Codes info", title:"Dx Codes", headerSort:false, cellClick:function(e, row, formatterParams){
const id = row.getData().account_num;
$(".diagnosisTable" + id + "").toggle();}
},
{title: "Account#",field: "account_num"},
{title: "Doctor",field: "doctor"},
{title: "Location", field: "location"},
],
rowFormatter: function(row, e) {
//create and style holder elements
var holderEl = document.createElement("div");
var tableEl = document.createElement("div");
const id = row.getData().account_num;
holderEl.style.boxSizing = "border-box";
holderEl.style.padding = "10px 10px 10px 10px";
holderEl.style.borderTop = "1px solid #333";
holderEl.style.borderBotom = "1px solid #333";
holderEl.style.background = "#ddd";
//holderEl.style.display = "none";
holderEl.setAttribute('class', "diagnosisTable" + id + "");
tableEl.style.border = "1px solid #333";
//tableEl.style.display = "none";
tableEl.setAttribute('class', "diagnosisTable" + id + "");
holderEl.appendChild(tableEl);
row.getElement().appendChild(holderEl);
//--------------------------------------------------------------- filter here?
let filterField = document.getElementById("filter-field");
document.getElementById("filter-trigger").addEventListener("click", function() {
console.log(filterField.value); // why is this not working?
diagnosisTable.setFilter("dx_code", "=", filterField.value);
table.redraw();
});
document.getElementById("clear-trigger").addEventListener("click", function() {
console.log(filterField.value); // why is this not working?
diagnosisTable.removeFilter("dx_code", "=", filterField.value);
table.redraw();
});
//--------------------------------------------------------------- filter ^here^?
var diagnosisTable = new Tabulator(tableEl, {
layout: "fitColumns",
data: row.getData().diagnosis_list,
index: "id",
columns: [
{title: "Num",field: "num"},
{title: "Dx Code",field: "dx_code"},
{title: "Type",field: "visit_type"},
{title: "P.O.A",field: "poa"}
]
}) // end of diagnosisTable tabulator
} // end of row formatter that hold diagnosisTable
}) // end of visitTable tabulator
} // end of row formatter that holds visitTable
}); // end of table tabulator
Please see my https://jsfiddle.net/zippyzuzka/zo3f5eqs/2/
Ideally, the table would initially display with every tier collapsed instead of each tier expanded (which I have coded), and still be able to filter via a 3rd tier property (which I do not have coded).
Also note that the entire data set - patient_data - is created after a form submit and sent to the table via AJAX, if that helps anything. (not in JSFiddle code however).
Also, I am extremely new to anything JavaScript, so my understanding is pretty little. I would imagine this would require maybe a custom filter of sorts? I've tried to add an event-click-listener to be able to table.setFilter("dx_code", "=", filterField.value); but it's not working. I don't know how to recursively retrieve the parent properties.
THANK YOU! THANK YOU!

Is it possible to plot "live data" in R language?

We want to plot live data in this site https://www.highcharts.com/demo/live-data is it possible to plot it with Highcharter library in R language if not is there any another solution to do that with R language?
Here is JavaScript code:
var defaultData = 'https://demo-live-data.highcharts.com/time-data.csv';
var urlInput = document.getElementById('fetchURL');
var pollingCheckbox = document.getElementById('enablePolling');
var pollingInput = document.getElementById('pollingTime');
function createChart() {
Highcharts.chart('container', {
chart: {
type: 'spline'
},
title: {
text: 'Live Data'
},
accessibility: {
announceNewData: {
enabled: true,
minAnnounceInterval: 15000,
announcementFormatter: function (allSeries, newSeries, newPoint) {
if (newPoint) {
return 'New point added. Value: ' + newPoint.y;
}
return false;
}
}
},
data: {
csvURL: urlInput.value,
enablePolling: pollingCheckbox.checked === true,
dataRefreshRate: parseInt(pollingInput.value, 10)
}
});
if (pollingInput.value < 1 || !pollingInput.value) {
pollingInput.value = 1;
}
}
urlInput.value = defaultData;
// We recreate instead of using chart update to make sure the loaded CSV
// and such is completely gone.
pollingCheckbox.onchange = urlInput.onchange = pollingInput.onchange = createChart;
// Create the chart
createChart();

How to copy data of html formatted cell instead of markup

I have some cells in Handsontable, that are displayed using "html" renderer. When I copy these cells and paste them in Excel, I get html content instead of data. Is there a way to display cells as they are, and get their value when copying ?
JSFiddle example:
example
document.addEventListener("DOMContentLoaded", function() {
var
data = [
{
title: "Title 1",
description: "<div style='text-align:right'>148</div>"
},
{
title: "Title 2",
description: "<div style='text-align:right'>2002</div>"
}
],
container1,
hot1;
container1 = document.getElementById('example1');
hot1 = new Handsontable(container1, {
data: data,
colWidths: [200, 200],
colHeaders: ["Title", "Description"],
columns: [
{data: "title", renderer: "html"},
{data: "description", renderer: "html"}
]
});
});
You can try converting your input data into json format and have a custom renderer which displays the value from json. Add a toString property to the data which will return exactly what you want to get copied.
Here is an updated fiddle: http://jsfiddle.net/mpusarla/gng4wqzy/6/
document.addEventListener("DOMContentLoaded", function() {
var item1 = {};
item1.title = "Title 1 ";
item1.description = {};
item1.description.text = "Desc 1";
item1.description.toString = function() {
return 'Updated Desc for 1';
}
var item2 = {};
item2.title = "Title 2";
item2.description = {};
item2.description.text = "Desc 2";
item2.description.toString = function() {
return 'Updated Desc for 2 ';
}
var data = [];
data.push(item1);
data.push(item2);
var container1, hot1;
function customRenderer(instance, td, row, col, prop, value, cellProperties) {
td.innerHTML = '<div style="text-align:right">' + value.text;
}
container1 = document.getElementById('example1');
hot1 = new Handsontable(container1, {
data: data,
colWidths: [200, 200],
colHeaders: ["Title", "Description"],
columns: [{
data: "title",
renderer: "text"
}, {
data: "description",
renderer: customRenderer
}]
});
});
</style><!-- Ugly Hack due to jsFiddle issue --> <script src="http://docs.handsontable.com/0.15.0/scripts/jquery.min.js"></script> <script src="http://docs.handsontable.com/0.15.0/bower_components/handsontable/dist/handsontable.full.js"></script> <link type="text/css" rel="stylesheet" href="http://docs.handsontable.com/0.15.0/bower_components/handsontable/dist/handsontable.full.min.css">
<div id="example1" class="hot handsontable"></div>

ChartJS Issues / Wordpress

I've got an issue with ChartJS. I've wanting to add charts to different areas of my site, and I've been able to get it to work with one chart but now I'm trying to add a separate chart (that isn't even on the same page as the first) and it won't load at all. It's the oddest thing.
Here's my script for the charts:
var wins = $("#wins").text();
var losses = $("#losses").text();
var draws = $("#draws").text();
var winsstrike = $("#wins-strike").text();
var winsgrapple = $("#wins-grapple").text();
var winssubmit = $("#wins-submit").text();
var winsother = $("#wins-other").text();
var recorddata = [{
value: 1*wins,
color: "#eb3f3d",
label: "Wins"
}, {
value: 1*losses,
color: "#ec582a",
label: "Losses"
}, {
value: 1*draws,
color: "#f8a430",
label: "Draws"
}
]
var recordoptions = {
animation: true,
segmentShowStroke : true,
segmentStrokeColor : "#191919",
percentageInnerCutout : 70
};
var winsdata = [{
value: 1*winsstrike,
color: "#eb3f3d",
label: "Strike"
}, {
value: 1*winsgrapple,
color: "#E82521",
label: "Grappling"
}, {
value: 1*winssubmit,
color: "#CB1815",
label: "Submission"
}, {
value: 1*winsother,
color: "#A61411",
label: "Other"
}
]
var winsoptions = {
animation: true,
segmentShowStroke : true,
segmentStrokeColor : "#191919",
percentageInnerCutout : 90
};
var c = $('#recordChart');
var ct = c.get(0).getContext('2d');
var ctx = document.getElementById("recordChart").getContext("2d");
myNewChart = new Chart(ct).Doughnut(recorddata, recordoptions);
var c1 = $('#winsbyChart');
var ct1 = c1.get(0).getContext('2d');
var ctx1 = document.getElementById("winsbyChart").getContext("2d");
myNewChart1 = new Chart(ct1).Doughnut(winsdata, winsoptions);
I have no clue why they won't work; the first chart, posting the #recordChart works flawlessly, but the second doesn't. I know the code is fine because I built a fiddle for it. I just can't figure out why the hell it won't work on the second chart (#winsbyChart).
Is there a conflict between the charts I'm not seeing? This is just so frustrating.
UPDATE:
I've deleted the first chart call (not the options or data), and the second appears. They seem to be conflicting with one another somehow. I'm also calling an external JS file; the script isn't embedded in my code. Below is the ENTIRE JS script - which is specifically used for these charts. Perhaps it's something to do with how I've set up the script file?
(function( root, $, undefined ) {
"use strict";
$(function () {
// DOM ready, take it away
var wins = $("#wins").text();
var losses = $("#losses").text();
var draws = $("#draws").text();
var winsstrike = $("#wins-strike").text();
var winsgrapple = $("#wins-grapple").text();
var winssubmit = $("#wins-submit").text();
var winsother = $("#wins-other").text();
var recorddata = [{
value: 1*wins,
color: "#eb3f3d",
label: "Wins"
}, {
value: 1*losses,
color: "#ec582a",
label: "Losses"
}, {
value: 1*draws,
color: "#f8a430",
label: "Draws"
}
]
var recordoptions = {
animation: true,
segmentShowStroke : true,
segmentStrokeColor : "#191919",
percentageInnerCutout : 80
};
var winsdata = [{
value: 1*winsstrike,
color: "#eb3f3d",
label: "Strike"
}, {
value: 1*winsgrapple,
color: "#E82521",
label: "Grappling"
}, {
value: 1*winssubmit,
color: "#CB1815",
label: "Submission"
}, {
value: 1*winsother,
color: "#A61411",
label: "Other"
}
]
var winsoptions = {
animation: true,
segmentShowStroke : true,
segmentStrokeColor : "#191919",
percentageInnerCutout : 80
};
var c = $('#recordChart');
var ct = c.get(0).getContext('2d');
var ctx = document.getElementById("recordChart").getContext("2d");
myNewChart = new Chart(ct).Doughnut(recorddata, recordoptions);
var c1 = $('#winsbyChart');
var ct1 = c1.get(0).getContext('2d');
var ctx1 = document.getElementById("winsbyChart").getContext("2d");
myNewChart1 = new Chart(ct1).Doughnut(winsdata, winsoptions);
});
} ( this, jQuery ));

Kendo TreeView Search with Highlight

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>

Categories