Highlight search keywords result - javascript

I am using the below search function in my table. I need to highlight any results matching with the keywords in the search input in the table. I am not sure how to add the scripting in. Kindly assist me on this as I am very new to Jscripting and still learning.
window.tableSearch = {};
tableSearch.init = function () {
this.Rows = document.getElementById('data').getElementsByTagName('TR');
this.RowsLength = tableSearch.Rows.length;
this.RowsText = [];
for (var i = 0; i < tableSearch.RowsLength; i++) {
this.RowsText[i] = (tableSearch.Rows[i].innerText) ? tableSearch.Rows[i].innerText.toUpperCase() : tableSearch.Rows[i].textContent.toUpperCase();
}
}
tableSearch.runSearch = function () {
this.Term = document.getElementById('textBoxSearch').value.toUpperCase();
for (var i = 0, row; row = this.Rows[i], rowText = this.RowsText[i]; i++) {
row.style.display = ((rowText.indexOf(this.Term) != -1) || this.Term === '') ? '' : 'none';
}
}
tableSearch.search = function (e) {
var keycode;
if (window.event) {
keycode = window.event.keyCode;
} else if (e) {
keycode = e.which;
} else {
return false;
}
if (keycode == 13) {
tableSearch.runSearch();
} else {
return false;
}
}

They people in this thread used a jQuery pluging to highlight the search string.
var words = "keyword1,keyword2,keyword3";
var keywords = words.split(',');
for(var i = 0; i < keywords.length; i++) {
$(selector).highlight($.trim(keywords[i]));
}
Is that something you could implement in your code as well?

Related

Error in validating my password with Javascript

I am trying to check my user inputted password with a series of if statements and boolean variables within a function. It seems like my if statements are not modifying my boolean variables. Could someone tell me why?
I was trying to use (/[a-zA-z]/).test(pValue.charAt(0))) as a boolean to see if the first character entry was a lower or upper case letter, but that didn't work either.
document.querySelector("#enter").addEventListener("click", validate);
function validate(e) {
var count = false;
var firstChar = false;
var hasNum = false;
var special = false;
var pValue = document.querySelector("#passwrd").value;
var pLength = pValue.length;
console.log(pValue);
console.log(pLength);
if(pLength > 4 && pLength <= 8) {
count = true;
}
if(pValue.search(e.charCode === [65 - 90]) === 0) {
firstChar = true;
}
console.log(firstChar);
for(var j = 0; j < pLength; j++) {
if(pValue.charAt(j) == "$" || pValue.charAt(j) == "%" || pValue.charAt(j) == "#") {
special = true;
}
}
for(var i = 0; i < pLength; i++) {
if(!isNaN(pValue.charAt(i))) {
hasNum = true;
}
}
if(count && firstChar && hasNum && special) {
document.querySelector("#show_word").textContent = pValue;
}
}

SAPUI5 Filter OData model based on fields using formatter

I have a List that contains ObjectListItems with content provided by an OData service. One of this contents is the title and the property has the value as follows:
title="{ path: 'title', formatter: 'app.schedule.util.Formatter.titleText'}"
As you can see there is a formatter in this title. The OData will bring a value like "available" or "disabled" and the formatter will transform it on the text for the specific language of the user.
I'm implementing a search capability on this List and it works fine, the problem is that it searchs only on the "available" and "disabled" values, and not in the formatted texts as it would be expected as this are not the values recognized by the user.
The filter code is:
handleSearch : function (evt) {
// create model filter
var filters = [];
var query = evt.getParameter("query");
if (query && query.length > 0) {
filters.push(new sap.ui.model.Filter("booked", sap.ui.model.FilterOperator.Contains, query));
filters.push(new sap.ui.model.Filter("weekday", sap.ui.model.FilterOperator.Contains, query));
filters.push(new sap.ui.model.Filter("title", sap.ui.model.FilterOperator.Contains, query));
filters = new sap.ui.model.Filter(filters, false);
}
// update list binding
var list = this.getView().byId("list");
var binding = list.getBinding("items");
binding.filter(filters);
},
Any idea on how to consider the formatter on the filter and not only the raw data?
Solution Considering you are doing only client side search:
Assumption: if you have grouping in the list..
handleSearch : function (evt) {
sFilterPattern = evt.getParameter("query");
sFilterPattern = sFilterPattern.toLowerCase();
var aListItems = this.getView().byId("list").getItems();
var bVisibility;
var oGroupItem = null;
var iCountInGroup = 0;
for (var i = 0; i < aListItems.length; i++) {
if (aListItems[i] instanceof sap.m.GroupHeaderListItem) {
if (oGroupItem) {
if (iCountInGroup == 0) {
oGroupItem.setVisible(false);
} else {
oGroupItem.setVisible(true);
oGroupItem.setCount(iCountInGroup);
}
}
oGroupItem = aListItems[i];
iCountInGroup = 0;
} else {
bVisibility = this.applySearchPatternToListItem(aListItems[i], sFilterPattern);
aListItems[i].setVisible(bVisibility);
if (bVisibility) {
iCountInGroup++;
}
}
}
if (oGroupItem) {
if (iCountInGroup == 0) {
oGroupItem.setVisible(false);
} else {
oGroupItem.setVisible(true);
oGroupItem.setCount(iCountInGroup);
}
}
}
applySearchPatternToListItem:function(oItem, sFilterPattern) {
if (sFilterPattern == "") {
return true;
}
//uncomment to search in oModel data
/*var oIteshellata = oItem.getBindingContext(this.sModelName).getProperty();
for (var sKey in oIteshellata) {
var sValue = oIteshellata[sKey];
// if (sValue instanceof Date) {
// //just for the filter take each number as string
// sValue = sValue.getDate() + "." +
// sValue.getMonth() + "." + sValue.getFullYear();
// }
if (typeof sValue == "string") {
if (sValue.toLowerCase().indexOf(sFilterPattern) != -1) {
return true;
}
}
}*/
// if nothing found in unformatted data, check UI elements
if ((oItem.getIntro() && oItem.getIntro().toLowerCase().indexOf(sFilterPattern) != -1)
|| (oItem.getTitle() && oItem.getTitle().toLowerCase().indexOf(sFilterPattern) != -1)
|| (oItem.getNumber() && oItem.getNumber().toLowerCase().indexOf(sFilterPattern) != -1)
|| (oItem.getNumberUnit() && oItem.getNumberUnit().toLowerCase().indexOf(sFilterPattern) != -1)
|| (oItem.getFirstStatus() && oItem.getFirstStatus().getText().toLowerCase().indexOf(sFilterPattern) != -1)
|| (oItem.getSecondStatus() && oItem.getSecondStatus().getText().toLowerCase().indexOf(sFilterPattern) != -1)) {
return true;
}
// last source is attribute array
var aAttributes = oItem.getAttributes();
for (var j = 0; j < aAttributes.length; j++) {
if (aAttributes[j].getText().toLowerCase().indexOf(sFilterPattern) != -1) {
return true;
}
}
return false;
}

How to get whether the pressed key is backspace or not in JavaScript?

I have a input text which used to filter data in a table using the onkeyup event
<input id="NameFilterText" type="text" onkeyup="return filterDataRow('NameFilterText','Name'); return false;" /></td>
I'm calling this JavaScript function in the onkeyup to the filter data
function filterDataRow(field, name) {
var textBox = document.getElementById(field);
var columnName = name;
var table = document.getElementById('table1');
var headRow = table.rows[0];
var column = 0
var text = textBox.value;
for (var i = 0; i < headRow.cells.length; i++) {
var cellName = headRow.cells[i].innerHTML;
if (cellName == columnName) {
column = i;
break;
}
}
for (var i = 1; i < table.rows.length; i++) {
table.rows[i].style.display = 'table-row'; // execute only when pressing backspace
for (var v = 0; v < text.length; v++) {
var CurCell = table.rows[i].cells[column];
var CurCont = CurCell.innerHTML.replace(/<[^>]+>/g, "");
var reg = new RegExp(text + ".*", "i");
if (CurCont.match(reg) == null) {
table.rows[i].style.display = 'none';
}
}
}
return false;
}
I don't want to execute that commented line if the pressed key is not backspace. How can I do that ?
var input = document.getElementById('NameFilterText');
var keydown=0;
input.onkeydown = function() {
var key = event.keyCode || event.charCode;
if( key == 8 || key == 46 )
keydown=1;
return false;
};
Now in your code filterDataRow()
if(keydown=1){ do your thing. and set keydown = 0 again}
Hope it Helps !
First you need to change the onkeyup event to this:
<input ... onkeyup="filterDataRow('NameFilterText','Name');" />
Then inside the function edit the line you want to be executed only one time adding this if-statement:
if (window.event.keyCode == 8) table.rows[i].style.display = 'table-row';
I wrote a library called keysight that does this kind of thing for all keyboard keys:
node.addEventListener("keydown", function(event) {
var key = keysight(event).key
if(key === '\b') {
console.log("We got one!")
}
})

mask work for id but not for class

hi i have a problem with my javascript code it works for input by id but i wat to use it on class element. I do not know what is i am doing wrong any idea? I paste my code
i want to mask time on my input
function maska(inputName, mask, evt) {
var text = document.getElementsByClassName(inputName);
try {
var value = $(text).val(); //text.value;
// Jeśli ktoś naciśnie dela lub backspace to czyszcze inputa
try {
var e = (evt.which) ? evt.which : event.keyCode;
if (e == 46 || e == 8) {
$(text).val() = ""; //text.value = "";
return;
}
} catch (e1) { }
var literalPattern = /[0\*]/;
var numberPattern = /[0-9]/;
var newValue = "";
for (var vId = 0, mId = 0; mId < mask.length; ) {
if (mId >= value.length)
break;
// Wpada jakaś inna wartość niż liczba przechowuje tylko ta dobra wartosc
if (mask[mId] == '0' && value[vId].match(numberPattern) == null) {
break;
}
// Wpadł literał
while (mask[mId].match(literalPattern) == null) {
if (value[vId] == mask[mId])
break;
newValue += mask[mId++];
}
var godzina = value.substr(0, 2);
var minuty = value.substr(3,4);
if (minuty > '59' || godzina > '23') {
break;
}
else
newValue += value[vId++];
mId++;
}
text.val() = newValue;
//text.value = newValue;
} catch (e) { }
}
getElementById returns a single DOMElement while getElementsByClass returns an array of elements. To allow for both, you could have one function that accepts a DOMElement and two functions that find the elements, one for id and one for class:
function maska(elem, mask, evt) {
try {
var value = $(elem).val();
// blah blah, rest of the function
}
function maskById(id, mask, evt) {
var element = document.getElementById(id);
maska(element, mask, evt);
}
function maskByClass(class, mask, evt) {
var element_list = document.getElementsByClass(class);
for(var i = 0; var i < element_list.length; i++) {
maska(element_list[i], mask, evt);
}
}
But you would be better off using the jquery selector combined with .each , which always returns results as a set/array, regardless of selector type.
document.getElementById returns a single element, which your code is written to handle.
document.getElementsByClassName returns multiple elements. You need to loop over them and process them each individually.
I don't get why you use getElementsByClassName and then use jQuery features?
try $('input.' + inputName)
getElementById returns a single element, while getElementsByClassName returns a collection of elements. You need to iterate over this collection
function maska(inputName, mask, evt) {
var text = document.getElementsByClassName(inputName);
try {
for (var i = 0; i < text.length; i++) {
var value = text[i].value;
// Jeśli ktoś naciśnie dela lub backspace to czyszcze inputa
try {
var e = (evt.which) ? evt.which : event.keyCode;
if (e == 46 || e == 8) {
text[i].value = "";
continue;
}
} catch (e1) { }
var literalPattern = /[0\*]/;
var numberPattern = /[0-9]/;
var newValue = "";
for (var vId = 0, mId = 0; mId < mask.length; ) {
if (mId >= value.length)
break;
// Wpada jakaś inna wartość niż liczba przechowuje tylko ta dobra wartosc
if (mask[mId] == '0' && value[vId].match(numberPattern) == null) {
break;
}
// Wpadł literał
while (mask[mId].match(literalPattern) == null) {
if (value[vId] == mask[mId])
break;
newValue += mask[mId++];
}
var godzina = value.substr(0, 2);
var minuty = value.substr(3,4);
if (minuty > '59' || godzina > '23') {
break;
}
else
newValue += value[vId++];
mId++;
}
text[i].value = newValue;
}
} catch (e) { }
}

Remove Required Field from QuickCreate in Sugarcrm

I wrote a function to remove accounts name relate field from Contacts QuickCreate but my function works in Firefox perfectly but in chrome its not working... Here is my function
function manageRequired(reqArr, disabledVal)
{
var requiredLabel = '<span class="required">*</span>'; // for firefox
var search_requiredLabel = '<span class="required"'; // searching string for firefox
var form = "";
for(var i = 0; i < document.forms.length; i++)
{
if(document.forms[i].id=='EditView')
{
form = 'EditView';
break;
}
if(document.forms[i].id=='form_SubpanelQuickCreate_Contacts')
{
form = 'form_SubpanelQuickCreate_Contacts';
break;
}
if(document.forms[i].id=='form_QuickCreate_Contacts')
{
form = 'form_QuickCreate_Contacts';
break;
}
if(document.forms[i].id=='form_QuickCreate_Accounts')
{
form = 'form_QuickCreate_Accounts';
break;
}
}
for(var j = 0; j < reqArr.length; j++)
{
var flag = true;
if (validate[form] != 'undefined')
{
for(var i = 0; i < validate[form].length; i++)
{
if(validate[form][i][0] == reqArr[j].id && validate[form][i][2])
{
if(disabledVal)
{
flag = false;
break;
}
else
{
validate[form][i][2] = false;
}
}
}
}
var labelNode = document.getElementById(reqArr[j].id + '_label');
if(flag & disabledVal)
{
// we require the field now
addToValidate(form, reqArr[j].id, reqArr[j].type, true,reqArr[j].label );
}
if(disabledVal)
{
if(labelNode != null && labelNode.innerHTML.indexOf(search_requiredLabel) == -1) // for IE replace search string
{
search_requiredLabel = '<SPAN class=required>';
}
if (labelNode != null && labelNode.innerHTML.indexOf(search_requiredLabel) == -1)
{
labelNode.innerHTML = labelNode.innerHTML.replace(requiredLabel, '');
labelNode.innerHTML = labelNode.innerHTML + requiredLabel;
}
}
else
{
if(labelNode != null)
{
if(labelNode != null && labelNode.innerHTML.indexOf("<SPAN class=required>*</SPAN>") == -1 && labelNode.innerHTML.indexOf('<span class="required">*</span>') == -1 )// for that field which is unrequired
{
}
else if(labelNode != null && labelNode.innerHTML.indexOf(requiredLabel) == -1) // for IE replace span string
{
requiredLabel = "<SPAN class=required>*</SPAN>";
}
labelNode.innerHTML = labelNode.innerHTML.replace(requiredLabel, '');
}
}
}
}
Can anyone please help me out to solve this issue...
To remove a required field from QuickCreate in Sugarcrm you can use this fuction:
removeFromValidate('EditView','eventlist_c');
or remove remove the validtion applied to the field:
$('#eventlist_c_label').html('{$mod_strings['LBL_EVENTLIST']}: ');

Categories

Resources