Server-side ajax search, wait till finish entering - Multi tables - javascript

I have the following code:
$('.gerais').each(function(){
var daotable = $(this).data('dao');
x = $(this).DataTable({
serverSide: true,
ajax: {
url: $('body').data('url')+'gerais/ajax_list/'+daotable,
type: "POST"
},
buttons: {
dom: {
button: {
className: 'btn btn-default'
}
},
buttons: [
{
extend: 'copyHtml5',
text: "<i class=' icon-copy3'></i> Copiar"
},
{
extend: 'excelHtml5',
text: "<i class=' icon-file-excel'></i> Excel"
},
{
extend: 'pdfHtml5',
text: "<i class=' icon-file-pdf'></i> PDF"
},
{
extend: 'print',
text: '<i class="icon-printer"></i> Imprimir'
}
],
}
});
});
$('.dataTables_filter input[type=search]').attr('placeholder','Pesquisar...')
.unbind()
.bind('input', function(e){
var item = $(this);
searchWait = 0;
if(!searchWaitInterval) searchWaitInterval = setInterval(function(){
if(searchWait >= 3){
clearInterval(searchWaitInterval);
searchWaitInterval = '';
searchTerm = $(item).val();
x[z].search(searchTerm).draw(); // change to new api
searchWait = 0;
}
searchWait++;
},200);
});
This part of the code is responsible for the loop that create data tables on my page, that have the class ".gerais":
$('.gerais').each(function(){
var daotable = $(this).data('dao');
x = $(this).DataTable({
serverSide: true,
ajax: {
url: $('body').data('url')+'gerais/ajax_list/'+daotable,
type: "POST"
},
buttons: {
dom: {
button: {
className: 'btn btn-default'
}
},
buttons: [
{
extend: 'copyHtml5',
text: "<i class=' icon-copy3'></i> Copiar"
},
{
extend: 'excelHtml5',
text: "<i class=' icon-file-excel'></i> Excel"
},
{
extend: 'pdfHtml5',
text: "<i class=' icon-file-pdf'></i> PDF"
},
{
extend: 'print',
text: '<i class="icon-printer"></i> Imprimir'
}
],
}
});
});
And this one is responsible by the delay on the search
$('.dataTables_filter input[type=search]').attr('placeholder','Pesquisar...')
.unbind()
.bind('input', function(e){
var item = $(this);
searchWait = 0;
if(!searchWaitInterval) searchWaitInterval = setInterval(function(){
if(searchWait >= 3){
clearInterval(searchWaitInterval);
searchWaitInterval = '';
searchTerm = $(item).val();
x[z].search(searchTerm).draw(); // change to new api
searchWait = 0;
}
searchWait++;
},200);
});
This works well for just one table, but I have 3 tables and it only works on the last one.
I already tried to transform "x" on a array and it didn't work.

I made some minor changes and tested it on two client side (serverSide:false) tables.
$(function () {
$("#tabs").tabs();
$('#tblTab1').DataTable();
$('#tblTab2').DataTable();
// definded global variable.
var searchWaitInterval = null;
$('.dataTables_filter input[type=search]').attr('placeholder', 'Pesquisar...')
.off()
.on('input', function (e) {
var item = $(this);
var searchWait = 0;
if (!searchWaitInterval) searchWaitInterval = setInterval(function () {
if (searchWait >= 3) {
clearInterval(searchWaitInterval);
searchWaitInterval = null;
searchTerm = $(item).val();
// aria-controls is an attribute added by DataTables so it makes it easy to target the right
// tables without resorting to global variables.
$("#" + item.attr("aria-controls")).DataTable().search(searchTerm).draw(); // change to new api
searchWait = 0;
}
searchWait++;
}, 200);
});
});

Related

Custom number of buttons tinymce

How can I create custom buttons tinymce buttons using JQuery? I would need n "Menu item" buttons. "n" would be defined depending on the selected data before opening the tinymce editor.
My buttons:
editor.addButton('addButtons', {
type: 'menubutton',
text: 'My button',
icon: false,
menu: [
{
text: 'Menu item 1',
onclick: function() {
editor.insertContent(' <strong>item1</strong> ');
}
}, {
text: 'Menu item 2',
onclick: function() {
editor.insertContent(' <strong>item2</strong> ');
}
}, {
text: 'Menu item 3',
onclick: function() {
editor.insertContent(' <strong>item3</strong> ');
}
}
]
});
I can get "n" value from a input type hidden using JQuery $("#totalButtons").val(). If totalButtons is 4, I would need 4 item buttons. Does it make sense? Is it possible to do?
Thanks
Updated Code:
var n = $('#total').val();
var menuItems = [];
tinymce.init({
selector: '#mytextareaTenant',
content_css: 'https://fonts.googleapis.com/css?family=Aguafina+Script|Alex+Brush|Bilbo|Condiment|Great+Vibes|Herr+Von+Muellerhoff|Kristi|Meddon|Monsieur+La+Doulaise|Norican|Nothing+You+Could+Do|Parisienne|Permanent+Marker|Sacramento|Yellowtail',
theme: 'modern',
menubar: false,
plugins: [
"print"
],
setup: function (editor) {
editor.on('init', function (e) {
renderEditorTenant();
for (var i=1; i<=n; i++){
var msg = ' <strong>#item' + i + '#</strong> ';
var obj = {
text: 'Menu item ' + i,
onclick: function() {
editor.insertContent(msg);
}
}
menuItems.push(obj);
}
});
Supposing you have a hidden input like this:
<input type="hidden" id="foo" name="zyx" value="3" />
You can get the value of the input and generate an array with n elements:
var n = $('#foo').val();
var menuItems = [];
for (var i=0; i<n; i++){
var msg = ' <strong>item' + i + '</strong> ';
var obj = {
text: 'Menu item ' + i,
onclick: function() {
editor.insertContent(msg);
}
}
menuItems.push(obj);
}
Now, just pass this array to the function you're using to generate the editor:
editor.addButton('addButtons', {
type: 'menubutton',
text: 'My button',
icon: false,
menu: menuItems
});

jQuery datatable - unexpected vertical scrollbar

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/

Why would blur event only fire one time? [duplicate]

I have a couple of drop downs that are populated from SharePoint using SPServices. This part works great. But then, I have a button that on click loads data from SharePoint and uses the dropdown texts as filter to fetch the data that will populate a table using the DataTables plugin. This part works only once; if I click the button again, nothing happens.
This is how I populate the dropdowns:
$(document).ready(function () {
var theYear; // Selected Year
var theRO; // Selected RO
//Fills the Dropdown lists (Year and RO)
$().SPServices({
operation: "GetListItems",
async: false,
listName: "{ListID}",
CAMLViewFields: "<ViewFields><FieldRef Name='Fiscal_x0020_Year' /><FieldRef Name='Regional_x0020_Office' /></ViewFields>",
completefunc: function (xData, Status) {
//Add Select Value option
$("#dropdown").prepend($('<option>', {
value: '',
text: 'Select Fiscal Year'
}));
$("#dropdownRO").prepend($('<option>', {
value: '',
text: 'Select Regional Office'
}));
//Fetching Data from SharePoint
$(xData.responseXML).SPFilterNode("z:row").each(function () {
var dropDown = "<option value='" + $(this).attr("ows_Fiscal_x0020_Year") + "'>" + $(this).attr("ows_Fiscal_x0020_Year") + "</option>";
var dropDownRO = "<option value='" + $(this).attr("ows_Regional_x0020_Office") + "'>" + $(this).attr("ows_Regional_x0020_Office") + "</option>";
$("#dropdown").append(dropDown);
$("#dropdownRO").append(dropDownRO);
/////////////Deletes duplicates from dropdown list////////////////
var usedNames = {};
$("#dropdown > option, #dropdownRO > option").each(function () {
if (usedNames[this.text]) {
$(this).remove();
} else {
usedNames[this.text] = this.value;
}
});
////Deletes repeated rows from table
var seen = {};
$('#myTable tr, #tasksUL li, .dropdown-menu li').each(function () {
var txt = $(this).text();
if (seen[txt]) $(this).remove();
else seen[txt] = true;
});
});
} //end of completeFunc
}); //end of SPServices
$('.myButton').on('click', function () {
run()
});
}); //End jQuery Function
This is the function I need to run every time I click on "myButton" after changing my selection in the dropdowns:
function run() {
theYear = $('#dropdown option:selected').text(); // Selected Year
theRO = $('#dropdownRO option:selected').text(); // Selected RO
var call = $.ajax({
url: "https://blah-blah-blah/_api/web/lists/getByTitle('Consolidated%20LC%20Report')/items()?$filter=Fiscal_x0020_Year%20eq%20'" + theYear + "' and Regional_x0020_Office eq '" + theRO + "'&$orderby=Id&$select=Id,Title,Fiscal_x0020_Year,Notices_x0020_Received,Declined_x0020_Participation,Selected_x0020_Field_x0020_Revie,Selected_x0020_File_x0020_Review,Pending,Pending_x0020_Previous_x0020_Yea,Controversial,GFP_x0020_Reviews,NAD_x0020_Appeals,Mediation_x0020_Cases,Monthly_x0020_Cost_x0020_Savings,Monthly_x0020_Expenditure,Regional_x0020_Office,Month_Number", //Works, filters added
type: "GET",
cache: false,
dataType: "json",
headers: {
Accept: "application/json;odata=verbose",
}
}); //End of ajax function///
call.done(function (data, textStatus, jqXHR) {
var oTable = $('#example').dataTable({
"aLengthMenu": [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
"iDisplayLength": -1, //Number of rows by default. -1 means All Records
"sPaginationType": "full_numbers",
"aaData": data.d.results,
"bJQueryUI": false,
"bProcessing": true,
"aoColumns": [{
"mData": "Id",
"bVisible": false
}, //Invisible column
{
"mData": "Title"
}, {
"mData": "Notices_x0020_Received"
}, {
"mData": "Declined_x0020_Participation"
}, {
"mData": "Selected_x0020_Field_x0020_Revie"
}, {
"mData": "Selected_x0020_File_x0020_Review"
}, {
"mData": "Pending"
}, {
"mData": "Pending_x0020_Previous_x0020_Yea"
}, {
"mData": "Controversial"
}, {
"mData": "GFP_x0020_Reviews"
}, {
"mData": "NAD_x0020_Appeals"
}, {
"mData": "Mediation_x0020_Cases"
}, {
"mData": "Monthly_x0020_Cost_x0020_Savings",
"fnRender": function (obj, val) {
return accounting.formatMoney(val);
}
}, {
"mData": "Monthly_x0020_Expenditure",
"fnRender": function (obj, val) {
return accounting.formatMoney(val);
}
}],
"bDeferRender": true,
"bRetrieve": true,
"bInfo": true,
"bAutoWidth": true,
"bDestroy": true,
"sDom": 'T&;"clear"&;frtip',
"oTableTools": {
"aButtons": ["xls"],
"sSwfPath": "../../Style Library/js/datatables/TableTools/media/swf/copy_csv_xls_pdf.swf",
},
"sSearch": "Filter",
"fnDrawCallback": function () {
//Add totals row
var Columns = $("#example > tbody").find("> tr:first > td").length;
$('#example tr:last').after('<tr><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td><td class="total"></td></tr>');
//Formating the Total row number to no decimals
$("#example tr:last td:not(:first,:last)").text(function (i) {
var t = 0;
$(this).parent().prevAll().find("td:nth-child(" + (i + 2) + ")").each(function () {
t += parseFloat($(this).text().replace(/[\$,]/g, '') * 1);
});
return parseInt(t * 100, 10) / 100;
});
//Format the monthly expenditure and savings to currency formatFormating the currency
var cell = new Array();
cell[0] = $('#example tr:last td:nth-child(12)').text();
cell[1] = $('#example tr:last td:nth-child(13)').text();
$('#example tr:last').find('td:nth-child(12)').html(accounting.formatMoney(cell[0]));
$('#example tr:last').find('td:nth-child(13)').html(accounting.formatMoney(cell[1]));
$('#example tr:last').find('td:last').hide();
} //hides extra td that was showing
}); //End of Datatable()
}); //End of call.done function
$('#theTableDiv').slideDown();
} //end of run() function
I'm not a programmer, I'm just trying to learn. I would appreciate any help. Thanks in advance
I would guess that you are replacing the part of the page where the button lives. (you really need to format your code more neatly for SO... use JSFiddle.net and their TidyUp button).
If that is the case you need to use a delegated event handler:
$(document).on('click', '.myButton', function () {
run()
});
This listens at a static ancestor of the desired node, then runs the selector when the event occurs, then it applies the function to any matching elements that caused the event.
document is the fallback parent if you don't have a convenient ancestor. Do not use 'body' for delegated events as it has odd behaviour.

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>

Creating Toolbar In Extjs 4.2 which should like Stack Overflow Toolbar

Am Creating Toolbar Which Is like Stack Overflow having Like This Am Creating Please Go Down you will see Pagination.Now Am stack in between how processed futhure .
i have created 4 buttons which are current page, its next page, and second and last page.
now i want to create next button on click of 2 page same. when i click on 2 page(ie 2nd button
then i want to create 3,4, button.. same way if i click on 6 than i wan to create next two button and prev button will seen which seen in above link.
my code is here:
Ext.define('Ext.bug.Newtoolbar', {
extend: 'Ext.toolbar.Toolbar',
alternateClassName: 'NewToolbar',
requires: ['Ext.toolbar.TextItem', 'Ext.button'],
mixins: {
bindable: 'Ext.util.Bindable'
},
autoDestroy: false,
displayInfo: false,
displayMsg: 'Displaying {0} - {1} of {2}',
emptyMsg: 'No data to display',
initComponent: function () {
var me = this,
pagingItems = me.addBtn(),
userItems = me.items || me.buttons || [];
if (me.prependButtons) {
me.items = userItems.concat(pagingItems);
} else {
me.items = pagingItems.concat(userItems);
}
//delete me.buttons;
if (me.displayInfo) {
me.items.push('->');
me.items.push({ xtype: 'tbtext', itemId: 'displayItem' });
}
me.callParent();
me.addEvents('change', 'beforechange');
me.on('beforerender', me.onLoad, me, { single: true });
me.bind(me.store || 'ext-empty-store', true);
},
// update here info...
updateInfo: function () {
var me = this,
displayItem = me.child('#displayItem'),
store = me.store,
pageData = me.getPageData(),
count, msg;
if (displayItem) {
count = store.getCount();
if (count === 0) {
msg = me.emptyMsg;
} else {
msg = Ext.String.format(
me.displayMsg,
pageData.fromRecord,
pageData.toRecord,
pageData.total
);
}
displayItem.setText(msg);
}
},
onLoad: function () {
var me = this,
pageData,
currPage,
pageCount,
afterText,
count,
isEmpty,
item;
count = me.store.getCount();
isEmpty = count === 0;
if (!isEmpty) {
pageData = me.getPageData();
currPage = pageData.currentPage;
pageCount = pageData.pageCount;
} else {
currPage = 0;
pageCount = 0;
}
Ext.suspendLayouts();
me.updateInfo();
me.updateLayout();
Ext.resumeLayouts(true);
if (me.rendered) {
me.fireEvent('change', me, pageData);
console.log('asd');
};
},
addBtn: function () {
var OnloadArray = [];
var me = this,
PageData,
currntPage,
PageCount;
PageData = me.getPageData();
currntPage = PageData.currentPage;
PageCount = PageData.pageCount;
for (var temp = 0; temp <= currntPage + 1; temp++) {
if (temp != 0) {
OnloadArray.push({
xtype: 'button',
itemId: temp,
scope: me,
text: temp,
enableToggle: true,
toggleGroup: me,
handler: me.btnHandler
});
}
};
OnloadArray.push({
xtype: 'tbtext',
scope: me,
text: '..........',
itemId: currntPage + 2
});
OnloadArray.push({
xtype: 'button',
itemId: PageCount - 1,
scope: me,
text: PageCount - 1,
enableToggle: true,
toggleGroup: me,
handler: me.btnHandler
});
OnloadArray.push({
xtype: 'button',
itemId: PageCount,
scope: me,
text: PageCount,
enableToggle: true,
toggleGroup: me,
handler: me.btnHandler
});
return OnloadArray;
},
getPageData: function () {
var store = this.store,
totalCount = store.getTotalCount();
return {
total: totalCount,
currentPage: store.currentPage,
pageCount: Math.ceil(totalCount / store.pageSize),
fromRecord: ((store.currentPage - 1) * store.pageSize) + 1,
toRecord: Math.min(store.currentPage * store.pageSize, totalCount)
};
}
});
please Help me Please
Thank You
Instead of coding it yourself, why not leverage off Ext JS's existing functionality?

Categories