Skip to content

Instantly share code, notes, and snippets.

@aayushdrolia
Last active August 10, 2021 11:19
Show Gist options
  • Save aayushdrolia/adb89446ea35102cc63d99a56a2b6124 to your computer and use it in GitHub Desktop.
Save aayushdrolia/adb89446ea35102cc63d99a56a2b6124 to your computer and use it in GitHub Desktop.
Select 2 basic usage with Group, Search & Highlights
Group, Simple Search, Highlight, Shorten Text with Tooltip
https://jsfiddle.net/gb7aju95/91/
Keyword Search, Highlight,
https://jsfiddle.net/bzotcxrp/92/
Keyword Search, Highlight,
https://jsfiddle.net/bzotcxrp/200/
Complete String with Keyword Search and Highlight
http://jsfiddle.net/vzLmwrc7/62/
Example:
function customMatcher(params, data) {
if ($.trim(params.term) === '') {
return data;
}
if (typeof data.text === 'undefined') {
return null;
}
if(params.term && params.term.length < 1){
return data;
}
let terms = params.term.toUpperCase().split(' ');
terms.unshift(params.term.toUpperCase().trim());
let text = data.text.toUpperCase();
terms = terms.filter(function(e) {
let temp = String(e).trim();
return (temp.length >= 1);
});
if(!terms.length){
return data;
}
var filteredChildren = [];
$.each(terms, function (id, term) {
if (text.indexOf(term) >= 0 && term.length >= 1) {
filteredChildren.push(data);
}
});
if (filteredChildren.length) {
var modifiedData = $.extend({}, data, true);
modifiedData.data = filteredChildren;
// You can return modified objects from here
// This includes matching the `children` how you want in nested data sets
return modifiedData;
}
// Return `null` if the term should not be displayed
return null;
}
function highlightMatched(element, term, highlightRecursively = true) {
var $result = $('<span></span>');
if(term.length < 1){
return $result.text(element.text);
}
let terms = term.toUpperCase().split(' ');
terms.unshift(term.toUpperCase().trim());
terms = terms.filter(function(e) {
let temp = String(e).trim();
return (temp.length >= 1);
});
if(!terms.length){
return $result.text(element.text);
}
terms = [...new Set(terms)];
removeHighlight(element.element);
if(element.text.toUpperCase().indexOf(terms[0].toUpperCase()) >= 0){
var regEx = new RegExp(terms[0], "ig");
highlight(element.element, regEx, highlightRecursively);
}else{
$.each(terms, function (id, searchTerm) {
let termMatch = element.text.toUpperCase().indexOf(searchTerm.toUpperCase());
// If there is a match, execute ins
if (termMatch >= 0) {
var regEx = new RegExp(searchTerm, "ig");
highlight(element.element, regEx, highlightRecursively);
}
});
}
return $result.html(element.element.innerHTML);
}
function highlight(node, regex, highlightRecursively, isRecursiveCall = false) {
var skip = 0;
if (3 === node.nodeType) {
var spannode, middleclone, middlebit = node.data.search(regex);
if(0 <= middlebit && 0 < node.data.length) {
middleclone = node.data.match(regex);
(spannode = document.createElement("span")).className = "highlight";
(middlebit = node.splitText(middlebit)).splitText(middleclone[0].length);
middleclone = middlebit.cloneNode(!0);
spannode.appendChild(middleclone);
middlebit.parentNode.replaceChild(spannode, middlebit);
skip = 1;
}
} else if (1 === node.nodeType && node.childNodes && !/(script|style)/i.test(node.tagName) && ("highlight" !== node.className || "SPAN" !== node.tagName))
for (var i = 0; i < node.childNodes.length; ++i){
if(!highlightRecursively){
if(!isRecursiveCall){
let temp = highlight(node.childNodes[i], regex, highlightRecursively, true);
if(temp == 1){
break;
}
}
}
else{
i += highlight(node.childNodes[i], regex, highlightRecursively);
}
}
return skip
}
function removeHighlight(element) {
return $(element).find("span.highlight").each(function() {
var parent = this.parentNode;
parent.replaceChild(this.firstChild, this);
parent.normalize();
}).end()
}
function registerAutoFocusEvent(element){
element.on('select2:open', () => {
document.querySelector('.select2-search__field').focus();
});
}
var query = {};
function mouldToSelect2(element, sort = false){
element.select2({
placeholder: "Your Placeholder",
allowClear: true,
width: '100%',
dropdownAutoWidth: true,
dropdownPosition: 'below',
matcher: customMatcher,
templateResult: function (item) {
if (item.loading) {
return item.text;
}
var term = query.term || '';
totalOptions = element.find('option') ? element.find('option').length : 0;
highlightRecursively = totalOptions > 2000 ? false : true;
var $result = highlightMatched(item, term, highlightRecursively);
return $result;
},
language: {
searching: function (params) {
// Intercept the query as it is happening
query = params;
// Change this to be appropriate for your application
return 'Searching…';
}
},
sorter: function(data) {
if(sort){
return data.sort(function(a, b) {
return a.text < b.text ? -1 : a.text > b.text ? 1 : 0;
});
}
return data;
}
}).on('select2:open', function(e){
$('.select2-search__field').attr('placeholder', 'Search');
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment