Search/filter for an array - javascript

I am making a search function for an array. I have a input[text] where for example I put 'ban', then I need all results that start with 'ban' to show up, for example banana, banana milkshake, banana(fried), etc.
How would I go about doing this? I tried, but every time I try it isn't accurate. What I tried is below.
What I have:
var inputBox = document.getElementById('ingredient');
var ingredienten = ["Appel", "Aardbei", "Aardappelen", "Banaan", "Bananen", "Banana"]
inputBox.onkeydown = function(evt) {
$("#autocomplete").empty();
// INSERT CODE FOR SEARCH FUNCTION
}
I had one that came very close, however when I typed 'ban' it came up with 'Aardbei'. Which is obviously wrong. Here it is, maybe I overlooked something?
var inputBox = document.getElementById('ingredient');
var ingredienten = ["banaan", "bananen", "baan", "banana", "baaanana"];
inputBox.onkeydown = function(evt) {
$("#autocomplete").empty();
var input, filter, a, i;
input = document.getElementById("myInput");
filter = inputBox.value.toUpperCase();
for (i = 0; i < ingredienten.length; i++) {
a = ingredienten[i];
if (a.toUpperCase().indexOf(filter) > -1) {
//console.log(a);
$("#autocomplete").append("<li>" + a + "</li>");
} else {
}
}

I think you should use the keyup event instead and you can make use of a regex and the filter function on the array of items:
var inputBox = document.getElementById('ingredient');
var ingredienten = ["Appel", "Aardbei", "Aardappelen", "Banaan", "Bananen", "Banana"]
inputBox.onkeyup = function(evt) {
$("#autocomplete").empty();
var query = $('#ingredient').val();
// escape regex
query = query.replace(
/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"
);
var queryRegExp = new RegExp('^' + query, 'i');
var results = ingredienten.filter(function(item) {
return queryRegExp.test(item);
});
results.forEach(function(item) {
$("#autocomplete").append("<li>" + item + "</li>");
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="ingredient" />
<div id="autocomplete"></div>

Using jQuery UI autocomplete this task can be done very easily:
$('#ingredient').autocomplete({
source: ["Appel", "Aardbei", "Aardappelen", "Banaan", "Bananen", "Banana"]
});
<link href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<input id="ingredient">

Going under the instructions, you can use a regular expression filter here on your array.
const results = ingredienten.filter(item => item.match(/^ban/)); //add i at the end to ignore case
This will iterate the array and return all the results that match the regex "starts with 'ban'".
You can also do a 0-2 substring match == 'ban' but that's a bit more manual.

Related

How to use different blogger post ID in Javascript variable?

I am trying to make every article views having comma separated every 3 digit number. I have found the code for that.
But I have problem to find specific blogger post ID to use for the code to work fine.
Here's the whole code that I am trying to work on.
<--Viewable area /-->
<span class='entry-time'><b:if cond='data:allBylineItems.author and data:allBylineItems.timestamp.label'><span class='on'><data:allBylineItems.timestamp.label/></span></b:if><time class='published' expr:datetime='data:post.date.iso8601'><data:post.date/></time></span><span class='postviews1' style='margin-left:5px; display:display;'><a expr:name='data:post.id'/> <i class='far fa-eye'/> <span id='bacani'><span id='postviews'/></span> Views</span>
<--comma separated every 3 digit /-->
<script>var angka = document.getElementById('bacani').textContent;var reverse = angka.toString().split('').reverse().join(''),ribuan = reverse.match(/\d{1,3}/g);ribuan = ribuan.join(',').split('').reverse().join('');document.getElementById('bacani').innerHTML= ribuan;</script>
<--code for views count /-->
<script src='https://cdn.firebase.com/v0/firebase.js' type='text/javascript'/> <script> $.each($("a[name]"), function(i, e) { var elem = $(e).parent().find("#postviews"); var blogStats = new Firebase("https://sh-v-3da10-default-rtdb.firebaseio.com/" + $(e).attr("name")); blogStats.once("value", function(snapshot) { var data = snapshot.val(); var isnew = false; if(data == null) { data= {}; data.value = 0; data.url = window.location.href; data.id = $(e).attr("name"); isnew = true; } elem.text(data.value); data.value++; if(window.location.pathname!="/") { if(isnew) blogStats.set(data); else blogStats.child("value").set(data.value); } }); });</script>
I want to change:
<span id='bacani'><span id='postviews'/></span>
and
document.getElementById('bacani').textContent;
to have a specific value id which is post id from blogger. The only thing that i found from internet is
<data:post.id>
Is there any other way that i can make it work other than what I am thinking right now? I think I need specific new id to make it work for every article to have comma separated every 3 digit.
I try to use the code but it only work for one time only. I believe to make it work as a whole I need to use different code to read specific unique id base on data:.post.id from blogger post id itself. But i do not sure how to make it work. I am expecting when I know how to use different method which is making new code that find unique id for different article it would work fine.
You can just replace elem.text(data.value) to
// original count
var count = data.value;
// count separated by comma
var separatedCount = count.toString()
.split('').reverse().join('')
.match(/\d{1,3}/g).join(',')
.split('').reverse().join('');
elem.text(separatedCount);
The full code would be
<!-- code for views count -->
<script src='https://cdn.firebase.com/v0/firebase.js' type='text/javascript'/>
<script>
/*<![CDATA[*/
$.each($("a[name]"), function (i, e) {
var elem = $(e).parent().find("#postviews");
var blogStats = new Firebase("https://sh-v-3da10-default-rtdb.firebaseio.com/" + $(e).attr("name"));
blogStats.once("value", function (snapshot) {
var data = snapshot.val();
var isnew = false;
if (data == null) {
data = {};
data.value = 0;
data.url = window.location.href;
data.id = $(e).attr("name");
isnew = true;
}
// original count
var count = data.value;
// count separated by comma
var separatedCount = count.toString()
.split('').reverse().join('')
.match(/\d{1,3}/g).join(',')
.split('').reverse().join('');
elem.text(separatedCount);
data.value++;
if (window.location.pathname !== "/") {
if (isnew) blogStats.set(data); else blogStats.child("value").set(data.value);
}
});
});
/*]]>*/
</script>

how to prevent users from writing some specific words in a textbox - JQuery

Is it possible to prevent users from typing or using some specific words in a textbox using JQuery or Javascript? For example, I have a textbox and I don't want users to use words like 'Phone', 'Home', 'Address' etc. Please Help.
This might be an option.
var txtBox = $('#text-box');
var blackList = ['Phone', 'Home', 'Address'];
function checkBlackList(str) {
$.each(blackList, function(i, n) {
if(new RegExp(n, "i").test(str)) {
txtBox.val(txtBox.val().replace(new RegExp(n, "gi"), "xxx"))
}
})
}
txtBox.on('keydown', function(e) {
checkBlackList(this.value);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<textarea name="" id="text-box" cols="30" rows="10"></textarea>
<input type="text" id="txt" />
<script>
$(document).ready(function(){
$("#txt").on("keydown", function(){
var text = $("#txt").val();
if(text.contains("Phone")){
$("#txt").val().replace("Phone", "");
}
if(text.contains("Home")){
$("#txt").val().replace("Home", "");
}
if(text.contains("Address")){
$("#txt").val().replace("Address", "");
}
});
});
</script>
You could check if a string contains a certain word:
if (yourVariable.indexOf("phone") >= 0){
alert('you may not use the word phone');
}
And if you want multiple words you could create an array and loop throug it.
var words = ['phone', 'home', 'address', 'bobba'];
for (i = 0; i < words.length; i++) {
if (yourVariable.indexOf(words[i]) >= 0){
alert('you may not use the word ' + words[i]);
}
}
and of course you can change the alert into anything you want like replace the text:
yourVariable.replace(words[i], 'xxx');
Edit i've made a fiddle: https://jsfiddle.net/jx8wd1br/1/
My proposal is based on:
array of forbidden words
Array forEach
String indexOf
String replace
var forbiddenWords = ['Phone', 'Home', 'Address'];
$(function () {
$('#myTxt').on('keyup', function(e) {
forbiddenWords.forEach(function(val, index) {
if (e.target.value.toUpperCase().indexOf(val.toUpperCase()) >= 0) {
e.target.value = e.target.value.replace(new RegExp( "(" + val + ")" , 'gi' ), '');
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="myTxt">
</form>

`Dynamically populate a dropdown menu using strings from a textarea

I want this coded in jquery preferably but normally, javascript is still fine by me.
The question is this:
I have a textarea and a dropdown menu on thesame page.
I can fill in text into the textarea by typing it or pasting it. The textarea on eachline contain emails and names seperated by comma.: Eg
email1#xyz.com, Richards Dough
email2#abc.com
EmilY34#yahoo.com , Emily Whites
Juniorpope4u#gmail.com , Junior
Mike87#yahoo.co.uk,
Ademola45thus#gmail.com, Ademola Erickson
etc
(notice the comma can be anywhere or even absent)
I want the dropdown menu to automatically be filled with the values of domain names of emails found on the textarea.
NOTE: There should NOT be duplicate listing in the dropdown and the listing should be alphabetically arranged in the dropdown
In my example, the dropdown will be be populated as below:
ALL
abc.com
gmail.com
xyz.com
yahoo.com
yahoo.co.uk
Default selected dropdown item has a value of ALL.
Please I know how to do this in php but have no clue about using javascript or jquery. Plus php have to refresh page to work but javascript wouldn't need page reloading
Hi Kindly check https://jsfiddle.net/pykmgyyt/5/ ...
jQuery
$(document).ready(function(){
var arr= new Array();
arr[0]="ALL"; //Setting fist element of the array to ALL
$('.btnUpdate').on('click', function(){
var newEmails=new Array();
var newEmails=$('.taEmails').val().split(/[ ,\r\n]+/); // get text area value and split text whenever jq encounters comma, space or newline and storing it into an array
/* Travese through newEMails array and push string which contains '#' in to arr array */
$.each(newEmails, function(i){
if (newEmails[i].indexOf('#') > -1){
arr.push(newEmails[i].substring(newEmails[i].indexOf("#") + 1)); /* Get only the domain names*/
console.log(newEmails[i]);
}
});
// check for duplicates
var result = [];
$.each(arr, function(i, e) {
if ($.inArray(e, result) == -1) result.push(e);
});
arr= result;
$('.ddEmails').empty(); // Empty dropdown
arr.sort(); // sort array
/*Append new array*/
$.each(arr, function(i){
$('.ddEmails').append("<option>"+arr[i]+"</option>");
//console.log(arr[i]);
}); /// arr each
}); // click
});
-split by comma and newline
-loop through each splited string
check whether it has # symbol
Find the domain and return
-display it in the select box
HTML
<textarea id="emails" onkeyup="finddomain();">
email1#xyz.com, Richards Dough
email2#abc.com
EmilY34#yahoo.com , Emily Whites
Juniorpope4u#gmail.com , Junior
Mike87#yahoo.co.uk,
Ademola45thus#gmail.com, Ademola Erickson
</textarea>
<select id="add_domain" name="add_domain">
</select>
Javascript
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">
function extractDomain(url) {
var ind=url.indexOf("#");
if (ind > 0)
{
var domain = url.substr((ind+1));
return domain;
}
else
return '';
}
function finddomain()
{
// You can do the below parts on javascript event
data = document.getElementById('emails').value;
var arr = data.split(/[\n,]+/); //data.split('\n');
var arrayLength = arr.length;
var sel = document.getElementById("add_domain");
for (var i = 0; i < arrayLength; i++) {
var domain = extractDomain(arr[i].trim());
if (domain != '' && $("#add_domain option[value='"+domain+"']").length == 0)
{
var option = document.createElement("option");
option.text = domain;
option.value = domain;
sel.appendChild(option);
}
}
}
</script>
Below part is to extract domains for multiple events
<script type="text/javascript">
$(document).ready(function() {
$('#emails').on('keyup keypress blur change', function(e) {
// e.type is the type of event fired
finddomain();
});
});
</script>

javascript match only certain letters in array

I'm using the below in a javascript Q & A chatbot. To answer for example "what is AG in the periodic table? Answer is Silver.
if ((input.search("(what is|what's)") != -1) && (input.search("(periodic table)") != -1)) {
document.result.result.value = "Hmmmm, I don't know. Try Google!";
for (i = 0; i < Periodic_Tables.length; i++) {
Periodic_Table = Periodic_Tables[i].split('=');
if (input.indexOf(Periodic_Table[0]) != -1) {
document.result.result.value = Periodic_Table[1];
}
}
return true;
}
Then I have in another file the array laid out like this:
Periodic_Tables=new Array(
"h=Hydrogen",
"he=Helium",
"li=Lithium",
"be=Beryllium",
"b=Boron",
"c=Carbon",
"n=Nitro­gen",
"o=Oxygen",
"f=Fluorine",
"ne=Neon",
"na=Sodium",
"mg=Magnesium",
"ag=Silver"
);
My problem is because the table symbols are only 1 or 2 letters it's matching a lot of wrong things. How can I set this up where "only" b matches boron, be matches beryllium. etc I've looked a word boundaries but can seem to figure out how to use them here.
Instead of this code block which is checking if input contains a symbol:
if (input.indexOf(Periodic_Table[0]) != -1) {
document.result.result.value = Periodic_Table[1];
}
You should check for equality like this:
Periodic_Tables=new Array("h=Hydrogen",
"he=Helium", "li=Lithium", "be=Beryllium", "b=Boron", "c=Carbon", "o=Oxygen",
"f=Fluorine", "ne=Neon", "na=Sodium", "mg=Magnesium", "ag=Silver");
function Parse(input) {
input=input.toLowerCase();
input=input.replace(/[!|?|,|.]/g,"");
if (input.search(/\bu\b/)!=-1) input=input.replace(/\bu\b/,"you");
if (input.search(/\br\b/)!=-1) input=input.replace(/\br\b/,"are");
if (input.search(/\bk\b/)!=-1) input=input.replace(/\bk\b/,"ok");
if (input.search(/\by\b/)!=-1) input=input.replace(/\by\b/,"why");
var words=input.split(" ");
var result = "Hmmmm, I don't know. Try Google!";
if ((input.search("(what is|what's)") != -1) && (input.search("(periodic table)") != -1)) {
for (var w=0; w<words.length; w++) {
for (i=0; i<Periodic_Tables.length; i++) {
Periodic_Table = Periodic_Tables[i].split('=');
if (words[w] == Periodic_Table[0]) {
result = Periodic_Table[1];
return result;
}
}
}
}
return result;
}
alert(Parse("what is h in periodic table"));
DEMO: http://jsfiddle.net/MnyFP/1/
First i'd use 2d array to store your periodic tables, so that you don't have to string split every time you want to use it.
Instead of
Periodic_Tables=new Array(
"h=Hydrogen",
"he=Helium",
"li=Lithium",
"be=Beryllium",
"b=Boron",
"c=Carbon",
"n=Nitro­gen",
"o=Oxygen",
"f=Fluorine",
"ne=Neon",
"na=Sodium",
"mg=Magnesium",
"ag=Silver",
);
Use
Periodic_Tables = [
["h", "Hydrogen"],
["he", "Helium"],
...
]
Assuming that the question is well formatted, that the symbol "AG" has a space in front and after it. I think you could simple test the input against " AG ", or " ag ", if you make it case insensitive. Including the spaces in the test string will for it to find matches that is a word in it self, instead of part of another word.
Pretty use regex has similar abilities, but i am not sure how to do it with regex..
assuming that the question in the chat box ends with the name of the element, u can split the string at the punctuations.(lets say user enters, what is,ag)
function abc(str)
{
String[] parts = str.split("\\W+");
var len=parts.length();
String sub=parts[len-1];
var re=new RegExp("^"+sub+"$","i");
and then use a loop and check the condition
if(re.test(arr[i])){
document.write(arr[i]);
break;
}
}
I would use an array of objects:
Periodic_Tables = [
{Symbol: "h", Element: "Hydrogen"},
{Symbol: "he", Element: "Helium"}
...
]
Then your loop looks like this:
for (i = 0; i < Periodic_Table.length; i++) {
if (input.indexOf(Periodic_Table[i].Symbol) !== -1) {
document.result.result.value = Periodic_Table[i].Element;
}
}
This prevents having to use a regex or a 2d array, and is a little more readable.
I can't seem to get anything to work within the Q and A bot. So I put up a demo here:
http://www.frontiernet.net/~wcowart/aademo.html
Or here is the code: I tried many of the various answers presented. Maybe I'm not implementing them right.
<HTML>
<HEAD>
<TITLE>ChatterBot Page</TITLE>
<script language="JavaScript">
Periodic_Tables=new Array(
"h=Hydrogen",
"he=Helium",
"li=Lithium",
"be=Beryllium",
"b=Boron",
"c=Carbon",
"n=Nitro­gen",
"o=Oxygen",
"f=Fluorine",
"ne=Neon",
"na=Sodium",
"mg=Magnesium",
"ag=Silver"
);
var message = new Array();
var randomnum;
var flagrandom;
function Parse() {
var input = new String(document.chat.input.value);
document.chat.input.value="";
input=input.toLowerCase();
word=input.split(" ");
num_of_words=word.length;
input=input.replace(/[!|?|,|.]/g,"");
word=input.split(" ");
if (input.search(/\bu\b/)!=-1) input=input.replace(/\bu\b/,"you");
if (input.search(/\br\b/)!=-1) input=input.replace(/\br\b/,"are");
if (input.search(/\bk\b/)!=-1) input=input.replace(/\bk\b/,"ok");
if (input.search(/\by\b/)!=-1) input=input.replace(/\by\b/,"why");
if ((input.search("(what is|what's)") != -1) && (input.search("(periodic table)") != -1)) {
document.result.result.value = "Hmmmm, I don't know. Try Google!";
for (var i = 0, len = Periodic_Tables.length; i < len; i++) {
if (Periodic_Tables[i].match('^'+input+'=')) {
document.result.result.value = Periodic_Tables[i].split('=')[1] }
}
return true;}
if (!flagrandom) {
randomnum = [Math.floor(Math.random()*3)]
flagrandom=true;}
message[0] = "Sorry, you stumped me on that one.";
message[1] = "Sorry, a search of my data base comes up empty.";
message[2] = "Not sure";
document.result.result.value = message[randomnum];
randomnum++
if (randomnum>2){randomnum=0}
return true;}
</script>
</head>
<BODY BACKGROUND="FFFFFF" TEXT="#0000cc" LINK="#FFCOOO" ALINK="#FFCC99"
VLINK="#FFC000" marginwidth="0" leftmargin="0" topmargin="0" rightmargin="0">
<Center>
<font size="+3">
ChatterBot
</font>
<br>
<img src="botpix.jpg" border="0" WIDTH="200" HEIGHT="200">
<br>
<form name="result">
<textarea rows=5 cols=40 input type="text" name="result">
</textarea><br>
</form>
</center>
<form name="chat" onSubmit="Parse();return false">
<b>Type here:</b>
<input type="text" name="input" size="100">
</form>
</body>
</html>

Hiding a div element with javascript

Following is the code where I display matched user input in the div but I want to hide the div when there is no match for user input. I can't seem to do it with the following code:
HTML code:
<input id="filter" type="text" placeholder="Enter your filter text here.." onkeyup = "test()" />
<div id="lc"> <p id='placeholder'> </p> </div>
JS code:
// JavaScript Document
s1= new String()
s2= new String()
var myArray = new Array();
myArray[0] = "Football";
myArray[1] = "Baseball";
myArray[2] = "Cricket";
myArray[3] = "Hockey";
myArray[4] = "Basketball";
myArray[5] = "Shooting";
function test()
{
s1 = document.getElementById('filter').value;
var myRegex = new RegExp((s1),"ig");
arraysearch(myRegex);
}
function arraysearch(myRegex)
{
document.getElementById('placeholder').innerHTML="";
for(i=0; i<myArray.length; i++)
{
if (myArray[i].match(myRegex))
{
document.getElementById('lc').style.visibility='visible';
document.getElementById('placeholder').innerHTML += myArray[i] + "<br/>";
}
else
{
document.getElementById('lc').style.visibility='hidden';
}
}
}
Regular expressions are a powerful tool but using them for so trivial a job is often troublesome.First you are using a direct input as regular expression which is never so good.
I copied your code and analyzed the logic you are making many many errors
for(i=0; i<myArray.length; i++)
{
if (myArray[i].match(myRegex))
{
document.getElementById('lc').style.visibility='visible';
document.getElementById('placeholder').innerHTML += myArray[i] + "<br/>";
}
else
{
document.getElementById('lc').style.visibility='hidden';
}
consider your code above, if I enter football, it matches with football, and football is shown. Next it checks for baseball which does not match and visibility changes to hidden!!
Better logic
1.Check what strings match, and add them to the division.
2.Check how many strings have matched, if none, change visibility to hidden.
You are using regular expressions when this actully can be achieved easily with indexOf();
these are pure logical errors
consider using jquery. (with a little http://underscorejs.org/ for utility)
var myArray = ["Football", "Baseball", "Cricket","Hockey", "Basketball", "Shooting"]
$("#filter").keyup(function() {
if(_.include(myArray, $(this).val()) {
$('#lc').show()
} else {
$('#lc').hide()
}
}

Categories

Resources