RGraph hide line plus labels with a click on key element - javascript

So, I have a graph like this:
What I'm trying to achieve is to hide the lines plus the labels with it when I click the key referring that line.
I found this on the docs and I tried doing this:
$(line.canvas).on('click', function (e) //line is the name of the graph of both green and red lines
{
var key = RGraph.Registry.get('key-element');
console.log(key);
if (key) {
console.log("true");
}
});
I found this to be pointless due the fact when I click on the keys they return weird outputs, either null or other key different from the one I want.
What I also found on RGraph Line API is that obj.hide([index]) only sets the color to rgba(0,0,0,0), which does not hide the labelsAbove property.
How can I fix this and make a proper hide of the lines when I click on the key?

Well this demo hides/shows the line but the labelsAbove labels are still there. So I'll have to look at this for the next beta.
Here's the code:
function createandcall(rackname, racknameid, stb) {
$('#maintable').append('<table class="table"><tbody><tr style="text-align:center"><td><h2>' + rackname + '</h2><table class="table"><tbody style="text-align:left"><tr id="STBL"></tr><tr id="STBL1"></tr><tr id="STBL2"></tr><tr id="STBL3"></tr></tbody></table></td></tr></tbody></table>');
for (i = 1; i < stb + 1; i++) {
createtable(i);
callstb(rackname, racknameid, i);
}
return;
}
function callstb(rackname, racknameid, i) {
$.ajax({
type: "GET",
dataType: 'text',
url: "http://localhost:3000/index/" + rackname + ' ' + racknameid + ' ' + i,
success: function (data) {
response = '\#stb' + i;
idtd = '\#tdstb' + i;
$(response).html(data.replace(/\[32m/gi, '').replace(/\[0\;33m/gi, '').replace(/\[0m/gi, '').replace(/\[33m/gi, '').replace(/\[37m/gi, '').replace(/\[31m/gi, ''));
pre = $(response).html().toString();
},
error: function (error) {
$("#error").html('Error trying to get the STBs report');
$("#error").show();
}
})
}
server.js:
app.get('/index/*', (req, res) => {
parsedparam = req.params[0].split(" ")
rackname = parsedparam[0]
racknameid = parsedparam[1]
stb = parseInt(parsedparam[2])
verifystbs(rackname, racknameid, stb, res);
});
function openconnection() {
con.connect(() => { console.log("RackChecker connected with database!") });
}
function closeconnection() {
con.end(() => { console.log("Connection Closed") });
}
function verifystbs(rackname, racknameid, stb, res) {
openconnection();
con.query("SELECT (SELECT UCASE(name) FROM models WHERE s.model = id) as Model,\
(SELECT UCASE(name) FROM manufacturers WHERE s.manufacturer = id) as Branch,\
(SELECT UCASE(name) FROM racks WHERE s.rack = id) as Rack,\
s.name as Stb,\
x.pr as Jira, \
x.reason as Reason,\
x.requestor AS Stress_Request,\
x.version as Version\
FROM \
stbs s \
LEFT JOIN \
stressrun x \
ON (s.active = 1 && s.rack = (SELECT id FROM racks WHERE name = '"+ racknameid + "')) \
WHERE x.id = (SELECT max(id) FROM stressrun y WHERE y.stb_id = s.id) and s.name like ('STB_%"+ stb + "')\
and x.reason in ('failed','other','new build') ORDER BY s.name;", (err, result) => {
console.log(result)
if (!Array.isArray(result) || !result.length) {
callnewstb = shell.exec('./shellscript/callnewstb.sh ' + rackname + ' ' + stb, { async: true });
callnewstb.stdout.on('data', (data) => {
res.send(data);
});
}
else {
for (i = 0; i < result.length; i++) {
parsestbnumber = result[i].Stb.split("_");
stbnumber = parseInt(parsestbnumber[1]);
stbnumber = stbnumber * 1;
if (stb == stbnumber) {
res.send("Stress Test is not running on <b>" + result[i].Stb + "</b><br>Reason: <b>" + result[i].Reason + "</b><br>Jira Ticket: <b><a href='https://link.jira.com/browse/" + result[i].Jira + "'>" + result[i].Jira + "</a></b><br>Build Version: <b>" + result[i].Version)
break
}
else {
callnewstb = shell.exec('./shellscript/callnewstb.sh ' + rackname + ' ' + stb, { async: true });
callnewstb.stdout.on('data', (data) => {
res.send(data);
})
}
}
}
});
closeconnection();
}

Related

How to correctly send data via ajax to telegram via php?

I made a questionnaire for the site on JS. JS works well, but it doesn't work correctly to send data via ajax to telegram. When sending, it hits error 400. If you set all the variables "hard" and not with a post like $the =question 6:; then everything is normal. It turns out I'm transmitting the data incorrectly. Tell me how to do it correctly.
Js works out as expected before sending it. Everything on the POST goes out(although it writes that everything was sent successfully)
function compileForm() {
// take answers
var answerInput1 = $('.qwestion-1:checked'),
answerInput2 = $('.qwestion-2:checked'),
answerInput3 = $('.qwestion-3:checked'),
answerInput4 = $('.qwestion-4:checked'),
answerInput5 = $('.qwestion-5:checked');
answerInput3Custom = $('#qwestion-3-custom');
scoreSum = answerInput1.data('cost') + answerInput2.data('cost') + answerInput3.data('cost') + answerInput4.data('cost') + answerInput5.data('cost');
var answer1 = answerInput1.val(),
answer2 = answerInput2.val(),
answer3 = answerInput3.val(),
answer4 = answerInput4.val(),
answer5 = answerInput5.val();
if (answerInput3.hasClass('qwestion-3-custom-choose')) {
console.log('another');
answer3 += ' - ' + answerInput3Custom.val();
}
// put unswers to inputs
var sendInp1 = $('#answer-1').val(answer1),
sendInp2 = $('#answer-2').val(answer2),
sendInp3 = $('#answer-3').val(answer3),
sendInp4 = $('#answer-4').val(answer4),
sendInp5 = $('#answer-5').val(answer5);
sendInp6 = $('#answer-6').val(scoreSum);
};
$('#final-qwestion__btn').click(function(e) {
e.preventDefault();
var answers = [];
$('.qwestion').each(function(index, el) {
var number = index + 1;
if (index > 4) {
answers.push(number + ') Номер телефона —— ' + $(this).find('#qwestion__tel-input').val() + '')
answers.push(number + ') Город : —— ' + $(this).find('#qwestion__gorod-input').val() + '')
} else if (index == 2) {
if ($(this).find('input:checked').hasClass('other')) {
answers.push(number + ') ' + $(this).find('.qwestion__heading').text() + ' —— ' + $(this).find('#qwestion-3-custom').val() + '')
} else {
answers.push(number + ') ' + $(this).find('.qwestion__heading').text() + ' —— ' + $(this).find('input:checked').val() + '')
}
} else {
answers.push(number + ') ' + $(this).find('.qwestion__heading').text() + ' —— ' + $(this).find('input:checked').val() + '')
}
});
if (!$('#qwestion__tel-input').val()) {
$('#qwestion__tel-input').css('box-shadow', '0 0 20px 0px #990033');
} else {
$('#qwestion__tel-input').css('box-shadow', 'none');
answers = answers.join('\n')
console.log(answers);
$.ajax({
url: 'send/send.php',
type: 'POST',
data: {
postData: answers
},
success: function(resultData){
alert("Save Complete");
}
})
}
});
});
<?php
if (isset($_POST['qwestion-1'])) {
$qwestionq = strip_tags($_POST['qwestion-1']);
$qwestionqFieldset = "<b>qwestion1:</b> ";
}
if (isset($_POST['qwestion-3'])) {
$qwestiona = strip_tags($_POST['qwestion-3']);
$qwestionaFieldset = "<b>qwestion2:</b>";
}
if (isset($_POST['qwestion-4'])) {
$qwestioz = strip_tags($_POST['qwestion-4']);
$qwestionzFieldset = "<b>qwestion3:</b> ";
}
if (isset($_POST['qwestion-5'])) {
$qwestionw = strip_tags($_POST['qwestion-5']);
$qwestionwFieldset = "<b>qwestion4:</b> ";
}
if (isset($_POST['qwestion-6'])) {
$qwestions = strip_tags($_POST['qwestion-6']);
$qwestionsFieldset = "<b>qwestion5:</b> ";
}
if (isset($_POST['gorod'])) {
$gorod = strip_tags($_POST['gorod']);
$gorodFieldset = "<b>qwestion6:</b> ";
}
if (isset($_POST['tel2'])) {
$tel = strip_tags($_POST['tel2']);
$telFieldset = "<b>qwestion7:</b> ";
}
$token = "";
$chat_id_scr = "";
$txt = rawurlencode($txt);
$arr = array(
$qwestionqFieldset => $qwestionq,
$qwestionaFieldset => $qwestiona,
$qwestionzFieldset => $qwestionz,
$qwestionwFieldset => $qwestionw,
$qwestionwFieldset => $qwestions,
$gorodFieldset => $gorod,
$telFieldset => $tel,
);
foreach($arr as $key => $value) {
$txt .= "<b>".$key."</b>".$value."%0A";
};
$sendToTelegram = fopen("https://api.telegram.org/bot{$token}/sendMessage?chat_id={$chat_id_scr}&parse_mode=html&text={$txt}","r");

I want to make a private chat for every user since all the user's chat are showing in a same view

I'm trying to make a chat application using spring boot and I am stuck. This is my Frontend (custom.js) code. I want to make a separate chat view for every specific user since all user's chat which is entered in this are showing on the same view. I have given an image link in this for a better explanation if anyone could help...
custom.js
let $chatHistory;
let $button;
let $textarea;
let $chatHistoryList;
function init() {
cacheDOM();
bindEvents();
}
function bindEvents() {
$button.on('click', addMessage.bind(this));
$textarea.on('keyup', addMessageEnter.bind(this));
}
function cacheDOM() {
$chatHistory = $('.chat-history');
$button = $('#sendBtn');
$textarea = $('#message-to-send');
$chatHistoryList = $chatHistory.find('ul');
}
function render(message, userName) {
scrollToBottom();
// responses
var templateResponse = Handlebars.compile($("#message-response-template").html());
var contextResponse = {
response: message,
time: getCurrentTime(),
userName: userName
};
setTimeout(function () {
$chatHistoryList.append(templateResponse(contextResponse));
scrollToBottom();
}.bind(this), 1500);
}
function sendMessage(message) {
let username = $('#userName').val();
console.log(username)
sendMsg(username, message);
scrollToBottom();
if (message.trim() !== '') {
var template = Handlebars.compile($("#message-template").html());
var context = {
messageOutput: message,
time: getCurrentTime(),
toUserName: selectedUser
};
$chatHistoryList.append(template(context));
scrollToBottom();
$textarea.val('');
}
}
function scrollToBottom() {
$chatHistory.scrollTop($chatHistory[0].scrollHeight);
}
function getCurrentTime() {
return new Date().toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3");
}
function addMessage() {
sendMessage($textarea.val());
}
function addMessageEnter(event) {
// enter was pressed
if (event.keyCode === 13) {
addMessage();
}
}
init();
chat.js
const url = 'http://localhost:8080';
let stompClient;
let selectedUser;
let newMessages = new Map();
function connectToChat(userName) {
console.log("connecting to chat...")
let socket = new SockJS(url + '/chat');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
console.log("connected to: " + frame);
stompClient.subscribe("/topic/messages/" + userName, function (response) {
let data = JSON.parse(response.body);
if (selectedUser === data.fromLogin) {
render(data.message, data.fromLogin);
} else {
newMessages.set(data.fromLogin, data.message);
$('#userNameAppender_' + data.fromLogin).append('<span id="newMessage_' + data.fromLogin + '" style="color: red">+1</span>');
}
});
});
}
function sendMsg(from, text) {
stompClient.send("/app/chat/" + selectedUser, {}, JSON.stringify({
fromLogin: from,
message: text
}));
}
function registration() {
let userName = document.getElementById("userName").value;
$.get(url + "/registration/" + userName, function (response) {
connectToChat(userName);
}).fail(function (error) {
if (error.status === 400) {
alert("Login is already busy!")
}
})
}
function selectUser(userName) {
console.log("selecting users: " + userName);
selectedUser = userName;
let isNew = document.getElementById("newMessage_" + userName) !== null;
if (isNew) {
let element = document.getElementById("newMessage_" + userName);
element.parentNode.removeChild(element);
render(newMessages.get(userName), userName);
}
$('#selectedUserId').html('');
$('#selectedUserId').append('Chat with ' + userName);
}
function fetchAll() {
$.get(url + "/fetchAllUsers", function (response) {
let users = response;
let usersTemplateHTML = "";
for (let i = 0; i < users.length; i++) {
usersTemplateHTML = usersTemplateHTML + '<a href="#" onclick="selectUser(\'' + users[i] + '\')"><li class="clearfix">\n' +
' <img src="https://rtfm.co.ua/wp-content/plugins/all-in-one-seo-pack/images/default-user-image.png" width="55px" height="55px" alt="avatar" />\n' +
' <div class="about">\n' +
' <div id="userNameAppender_' + users[i] + '" class="name">' + users[i] + '</div>\n' +
' <div class="status">\n' +
' <i class="fa fa-circle offline"></i>\n' +
' </div>\n' +
' </div>\n' +
' </li></a>';
}
$('#usersList').html(usersTemplateHTML);
});
}

NodeJS SQL Server - Running multiple queries with Async

I'm attempting to run two separate queries in a NodeJS Lambda Function. The first inserts a single record, and will return an order number used in the subsequent queries. The second query needs to insert n records (order items), so I've been trying to execute those utilizing the async node library as you can see below.
I'm running into issues where it's either not executing those queries at all, or is only inserting a single record versus n records. I'm feeding it right now with an API request, so the referenced items array should have two indexes in it, resulting in two iterations.
const sql = require('mssql');
const async = require('async');
(function() {
// ——- Database support ——- //
exports.handler = function(event, context, callback)
{
const config = {
user: 'my_user',
password: 'my_pass',
server: 'my_serv',
database: 'my_db',
options: {
encrypt: true
}
};
// Request Body
var body = event;
var items = body[1]["items"];
var addDateTimeRaw = body[1]["created_at"];
var splitDateTime = addDateTimeRaw.split(" ");
// SPROC params
var CustomerNumber = "1234";
var OrderDateString = splitDateTime[0];
var ShipVia = "UPS";
var FOB = "null";
var PaymentTerms = "CREDIT CARD";
var Discount = "0";
var OrderAmount = body[1]["total_price"].cents;
var PONumber = body[1]["_id"];
var Comment = "I am a comment";
var SalesPerson = "WA";
var IsShippingSameAsBilling = "X";
var TaxableAmount = body[1]["total_value"].cents;
var TaxState = "my_state";
var AddDate = splitDateTime[0];
var AddTime = splitDateTime[1];
var WebOrderNumber = body[1]["_id"];
sql.connect(config, (err) => {
if (err) {
console.log(err);
callback(err);
} else {
const req = new sql.Request();
req.query('EXEC InsertOrder #CustomerNumber = "' + CustomerNumber + '", #OrderDateString = "' + OrderDateString + '", #ShipVia = "' + ShipVia + '", #FOB = "' + FOB + '", #PaymentTerms = "' + PaymentTerms + '", #Discount = "' + Discount + '", #OrderAmount = "' + OrderAmount + '", #PONumber = "' + PONumber + '", #Comment = "' + Comment + '", #SalesPerson = "' + SalesPerson + '", #IsShippingSameAsBilling = "' + IsShippingSameAsBilling + '", #TaxableAmount = "' + TaxableAmount + '", #TaxState = "' +TaxState + '", #AddDate = "' + AddDate + '", #AddTime = "' + AddTime + '", #WebOrderNumber = "' + WebOrderNumber + '";', (error, result) => {
if (error) {
console.log(error);
callback(error);
} else {
var OrderNumber = result.recordset[0].sono;
insertOrderItems(OrderNumber);
sql.close();
context.succeed(result.recordset)
return JSON.stringify(items);
}
});
function insertOrderItems(OrderNumber) {
async.forEachOf(items, function (item, i, inner_callback){
//var itemNumber = item["sku"];
var ItemNumber = "5678";
var DiscountPercent = "0";
var TaxRate = "6";
var Quantity = item["quantity"];
var ItemSequence = i + 1;
var CustomerMemo = "I am a memo";
var UnitPrice = "6.00";
var ssql = 'EXEC InsertOrderItems #OrderNumber = "' + OrderNumber + '", #ItemNumber = "' + ItemNumber + '", #DiscountPercent = "' + DiscountPercent + '", #TaxRate = "' + TaxRate + '", #Quantity = "' + Quantity + '", #ItemSequence = "' + ItemSequence + '", #CustomerMemo = "' + CustomerMemo + '", #UnitPrice = "' + UnitPrice + '";';
req.query(ssql, function(err, members, fields){
if(!err){
console.log(members);
//context.succeed(members.recordset)
inner_callback(null);
} else {
console.log("Error while performing Query");
inner_callback(err);
};
});
}, function(err){
if(err){
//handle the error if the query throws an error
callback(err);
}else{
//whatever you wanna do after all the iterations are done
callback(null);
}
});
}
}
});
sql.on('error', (err) => {
console.log(err);
callback(err);
});
};
}());
Why might that function call to the async SQL query not be executing? I'm attempting to keep the same SQL connection open for both of the executed queries.
The async is not a main issue. I patched some places but it still worse.
Why do you not learn step-by-step?
const sql = require('mssql');
const async = require('async');
const config = { ... };
exports.handler = function(event, context, callback) {
// Use default object with props or check existing of every props
var body = (event && event[1]) instanceof Object ? event[1] : {items: [], created_at: ' ', _id: ...};
var items = body.items || []; // Always use default value
var [addDate, addTime] = (created_at || '').split(' '); // Use destructuring assignment
// SPROC params
var CustomerNumber = "1234";
var OrderDateString = splitDateTime[0];
var ShipVia = "UPS";
var FOB = "null";
var PaymentTerms = "CREDIT CARD";
var Discount = "0";
var OrderAmount = parseFloat((body.total_price || {}).cents) || 0; // total_price can be non-object and it'll fall your app
var PONumber = body[1]["_id"];
var Comment = "I am a comment";
var SalesPerson = "WA";
var IsShippingSameAsBilling = "X";
var TaxableAmount = body[1]["total_value"].cents;
var TaxState = "my_state";
var WebOrderNumber = body._id;
sql.connect(config, (err) => {
// Early quit to avoid {}-ladder
if (err)
return callback(err);
const req = new sql.Request();
// Never do like this. Read about sql-injection. Use placeholders.
req.query('EXEC ost_InsertOrder #CustomerNumber = "' + ..., (err, result) => {
if (err)
return callback(err);
var OrderNumber = result.recordset.length && result.recordset[0].sono; // You must be sure that result has rows
// You should read about async-code
insertOrderItems(OrderNumber); // Here you start to insert items
sql.close(); // But before it'll success you close connection.
context.succeed(result.recordset);
// I didn't see definition of items.
// Return? For what?
return JSON.stringify(items);
});
...
}
});
sql.on('error', callback);
};

beaglebone black not receiving serial bonescript

Beaglebone black - not receiving data on serial. I have connected Tx and Rx pins of the serial ports 1 and 2 directly (tx - rx). I'm kind of new to beaglebone. I used this code to send data on the serial to another device, it worked properly for transmission, but not for Rx.
I haven't found the file ttyO1, just ttyO2.
var b = require('bonescript');
var rxport = '/dev/ttyO1';
var txport = '/dev/ttyO2';
var options = { baudrate: 115200, parity: 'even', parser:
b.serialParsers.readline('\n') };
var teststring = "This is the string I'm sending out as a test";
b.serialOpen(rxport, options, onRxSerial);
function onRxSerial(x) {
console.log('rx.eventrx= ' + x.event);
if(x.err) throw('***FAIL*** ' + JSON.stringify(x));
if(x.event == 'open') {
//readReapeatedly();
b.serialOpen(txport, options, onTxSerial);
}
if(x.event == 'data') {
console.log("I am receiving on rxport");
console.log('rx (' + x.data.length +
') = ' + x.data.toString('ascii'));
}
}
function onTxSerial(x) {
console.log('tx.event = ' + x.event);
if(x.err) throw('***FAIL*** ' + JSON.stringify(x));
if(x.event == 'open') {
writeRepeatedly();
}
if(x.event == 'data') {
console.log('tx (' + x.data.length +
') = ' + x.data.toString('ascii'));
console.log(x.data);
}
}
function printJSON(x) {
console.log(JSON.stringify(x));
}
function writeRepeatedly() {
console.log("write to serial");
b.serialWrite(txport, teststring, onSerialWrite);
console.log("I have sent data");
}
function onSerialWrite(x) {
console.log("Iam in the onSerialWrite function");
if(x.err) console.log('onSerialWrite err = ' + x.err);
if(x.event == 'callback') {setTimeout(writeRepeatedly, 5000);
console.log("HERE");
}
}

javascript comparing input to an array live search

So I'm working on this Zipline for my free code camp and am pretty much done, i'm just trying to implement a search. I have it working ok but have a couple of bugs.
What i'm doing for the search is that i'm creating a new array then i'm filtering it and comparing it to the text input of the user and if its equal then i will push that value onto a new array then display it on the screen.
is there a better way to do this? so that as the user types it is comparing with the list of arrays I have.
Thanks
Here is the jsfiddle http://jsfiddle.net/wtj7s6c6/2/
$(document).ready(function () {
var img, user, status, channel,
url = "https://api.twitch.tv/kraken/",
/* cb = '?client_id=5j0r5b7qb7kro03fvka3o8kbq262wwm&callback=?',*/
cb = '?callback=?',
//create new array from filtered array
newArray = [],
userList = ["freecodecamp", "maximilian_dood", "UltraChenTV", "habathcx", "TeamSpooky", "Nuckledu", "medrybw"];
/*function updateLog(message) {
$("#log").html($("#log").html() + "<p>" + message + "</p>");
};*/
function addOnlineUser(image, username, status) {
$(".people")
.append('<li><img class="picture" src="' + image + '"/><span class="username">' + username + '</span><span class="isOnline">✔</span><p class="status">' + status + '</p></li>');
};
function addOfflineUser(image, username) {
if (image != null) $(".people")
.append('<li><img class="picture" src="' + image + '"/> <span class="username">' + username + '</span><span class="isOffline">!</span></li>');
else $(".people")
.append('<li><img class="picture emptypic"/><span class="username">' + username + '</span><span class="isOffline">!</span></li>');
};
function clickOnline() {
userList.forEach(function (name) {
$.getJSON(url + 'streams/' + name + cb)
.success(function (data) {
if (data.stream !== null) {
img = data.stream.channel.logo;
user = data.stream.channel.display_name;
status = data.stream.channel.status;
channel = data._links.channel;
addOnlineUser(img, user, status);
}
});
});
};
function clickOffline() {
userList.forEach(function (name) {
$.getJSON(url + 'streams/' + name + cb)
.success(function (data) {
if (data.stream === null) {
$.getJSON(url + 'users/' + name + cb)
.success(function (data2) {
img = data2.logo;
user = data2.display_name;
channel = data2._links.self;
addOfflineUser(img, user);
});
}
});
});
};
function clickSearchOff(array) {
array.forEach(function (name) {
$.getJSON(url + 'streams/' + name + cb)
.success(function (data) {
if (data.stream === null) {
$.getJSON(url + 'users/' + name + cb)
.success(function (data3) {
img = data3.logo;
user = data3.display_name;
channel = data3._links.self;
addOfflineUser(img, user);
});
}
});
});
};
function clickSearchOn(array) {
array.forEach(function (name) {
$.getJSON(url + 'streams/' + name + cb)
.success(function (data4) {
if (data4.stream !== null) {
img = data4.stream.channel.logo;
user = data4.stream.channel.display_name;
status = data4.stream.channel.status;
channel = data4._links.channel;
addOnlineUser(img, user, status);
}
});
});
};
$(".online").on('click', function () {
$(".people").empty();
clickOnline();
});
$(".offline").on('click', function () {
$(".people").empty();
clickOffline();
});
$(".all").on('click', function () {
$(".people").empty();
clickOnline();
clickOffline();
});
$(".all").click();
$('input[type="text"]').keyup(function () {
var searchTerm = $(this).val();
searchTerm = searchTerm.toLowerCase();
console.log("Search term:" + searchTerm);
//empty screen//
$(".people").empty();
var newArray = [];
for (var i = 0; i < userList.length; i++) {
if (userList[i].indexOf(searchTerm) != -1) {
newArray.push(userList[i]);
}
}
console.log("New array: " + newArray);
clickSearchOff(newArray);
clickSearchOn(newArray);
});
})
I suggest (as I may do) implement some kind of buffer on the keyup event in order to not always trigger the comparison, only after one or two seconds pass after the last keyup trigger:
var compareTimeout;
$('input[type="text"]').keyup(function () {
clearTimeout(compareTimeout);
compareTimeout = setTimeout(function () {
var searchTerm = $(this).val();
searchTerm = searchTerm.toLowerCase();
console.log("Search term:" + searchTerm);
//empty screen//
$(".people").empty();
var newArray = [];
for (var i = 0; i < userList.length; i++) {
if (userList[i].indexOf(searchTerm) != -1) {
newArray.push(userList[i]);
}
}
console.log("New array: " + newArray);
clickSearchOff(newArray);
clickSearchOn(newArray);
}, 2000);
});
This would make the function run only after 2 seconds after the last keyup event, and not every time the user types a letter in the input.

Categories

Resources