Searching and highlighting can be implemented as a combination of two existing features:
- common data filtering,
- specific template of the column (for datatable) or of the component (for list and dataview).
In short, all you need to is:
- Remember searched text
- Use it for data filtering
- Use it in the template to find and mark all text occurences
In this example, the UI consists of two widgets: a Text view (standalone input for filtering) and a Datatable.
First, let's setup the onTimedKeyPress
handler for the Text input. Here we can get the current value of the input and use it for data filtering.
// in Text configuration:
on: {
onTimedKeyPress: function() {
const value = this.getValue();
findText(value);
}
}
The findText
will activate filtering and make sure the value is stored somewhere for further usage. We'll also use a RegExp to escape special characters in the stored value, if there's any:
function findText(text) {
/* store text that should be highlighted */
text = text || "";
escapedSearchText = text.replace(charactersSet, "\\$&");
/* filter data */
table.filter(filteringFunction)
};
As we have already called filtering, the Datatable will show the results. This is the moment when the filtered data is rendered according to the related template.
view:"datatable",
columns:[{
id:"title",
template: searchColumnTemplate
}],
We'll use another RegExp to find the searched text and add a span
with a specific CSS for it:
function searchColumnTemplate(data, type, value) {
let search = escapedSearchText;
if (search) {
value = addTextMark(value, search);
}
return value;
};
function addTextMark(value, text) {
const checkOccurence = new RegExp("(" + text + ")", "ig");
return value.replace(
checkOccurence,
"<span class='search_mark'>$1</span>"
);
}