How to check text input changes for certain words? - javascript

I need to create a web page on which I have added a text field. I have set an ID to the text field (say, 'custom'). Now, I want to modify the webpage if the text field contains certain words.
For example, if the text field contains a word, say apple, I want to do something.
If the text field contains ball, I want to do something else.
And so on.
I had found this:
<script>
var check=document.getElementById("custom").value == "text_value";
//check will be true or false
if (check){ //do something if true}
if(!check){//do something if false}
</script>
I don't even know if it's correct or not, but, I realised, it won't be able to manage multiple conditions. Because, if the text contains apple, it won't contain ball, it will create wierd behaviour.
So, how can I achieve this?

Check out the following Vanilla JavaScript (plain JavaScript) example.
I.e. enter bla bla apple and you will get the expected result.
function doSomething() {
var text = document.getElementById("myInput").value;
if (text.includes("apple")) {
console.log("do something special because text contains apple");
}
else if (text.includes("ball")) {
console.log("do something special because text contains ball");
}
else {
console.log("text contains no special word");
}
}
Enter text: <input type="text" id="myInput" onkeyup="doSomething()">

Can you please run the code snippet below.
The trigger is onkeyup and was selected for demonstration purposes. You can change it as per your requirement, for example, run the javascript function watchWords upon pressing a button.
function watchWords()
{
var watch_words = ['apple', 'lemon', 'watermelon'];
var textvalue = document.getElementById('name').value;
for(var i=0; i<watch_words.length; i++) {
if (~textvalue.indexOf(watch_words[i])){
if(watch_words[i] == 'apple'){
console.log('Apple was found');
}
if(watch_words[i] == 'lemon'){
console.log('Lemon was found');
}
if(watch_words[i] == 'watermelon'){
console.log('Watermelon was found');
}
}
}
}
<input type="text" name="name" id="name" onkeyup="watchWords()" />

One option is to use an object indexed by the .values you want to identify, whose property values are the functions you you want to run for each, eg:
const objOfFns = {
apple() {
console.log('Apple!');
},
ball() {
console.log('Ball!');
bounceBall();
}
};
const { value } = document.getElementByid('custom');
const possibleFn = objOfFns[value];
// check hasOwnProperty to avoid accidentally referencing Object.prototype methods
if (possibleFn && objOfFns.hasOwnProperty(value) {
possibleFn();
}

Using jQuery on keyup event listener and includes function:
$("#custom").on("keyup", function() {
if (this.value.includes("apple")) {
// do something
}
});
The code above will check the custom input each time the user presses a key and execute the if block if the input string contains the word apple.

<script>
function common(arr1, arr2) {
var newArr = [];
newArr = arr1.filter(function(v){ return arr2.indexOf(v) >= 0;})
newArr.concat(arr2.filter(function(v){ return newArr.indexOf(v) >= 0;}));
return newArr;
}
var string = document.getElementById("custom").value;
var items = string.split(" ");
var yourlist = ["apple", "banana", "tomato"];
var intersection = common(yourlist, items);
for(i=0; i<intersection.length; i++){
console.log(intersection[i]);
var z = yourlist.indexOf(intersection[i]);
/* Your Logic Goes Here.. */
if(z == 0){
/* do something */
}else{
/* do something else */
}
}
</script>
Function Credits - https://gist.github.com/IAmAnubhavSaini

Related

input box asking for two specific words

I'm new to this, so I hope I can explain well enough what my problem is.
I've got a quiz and for an answer I created an input box. To get to another link you have to put two words in there but the order should not matter aka. it shouldn't matter if you write down "word1 word2" or "word2 word1", there should be only one rule: both words should be mentioned.
Is that possible?
My code so far:
function checkText()
{
var textwunf_1 = document.getElementById("wunf").value;
if(textwunf_1.toLowerCase() == "word1" && "word2"){
window.open("URL","_self");
}
else{
xxx
}
}
It does not work.
Before I only wanted to check if one word is used, like that:
var textwunf_2 = 'word1';
function checkText()
{
var textwunf_1 = document.getElementById("wunf").value;
if(textwunf_1.toLowerCase().indexOf(textwunf_2) == -1){
xxx
}
else{
window.open("URL","_self");
}
}
This worked but I can't use it for two words, because if I write
var textwunf_2 = 'word1 word2';
the order can't be 'word2 word1'...
Is there a solution to my problem?
Hopefully anyone can understand and help me, thank you!
Based on this commentary from the OP:
if the user types 3 words and two of them match with the answer, it should be also okay! even better if even 3 words or more are possible, as long as the user puts my two words in it..
You can check if both words are whitin the text using two conditions on the if:
textwunf_1.toLowerCase().indexOf("word1") >= 0
AND
textwunf_1.toLowerCase().indexOf("word2") >= 0
Try with the next code:
var textwunf_2 = 'word1';
var textwunf_3 = 'word2';
function checkText()
{
var textwunf_1 = document.getElementById("wunf").value;
if ((textwunf_1.toLowerCase().indexOf(textwunf_2) >= 0) &&
(textwunf_1.toLowerCase().indexOf(textwunf_3) >= 0))
{
window.open("URL","_self");
}
else
{
// xxx
}
}
Another approach:
var words = ["word1", "word2"];
function CheckWords() {
var inputWords = document.getElementById("wunf").value.split(' ');
var allWordsFound = true;
if (inputWords.length !== words.length) { return false; }
inputWords.forEach(function(word) {
if (words.indexOf(word.toLowerCase()) === -1) {
allWordsFound = false;
return;
}
});
return allWordsFound;
}
console.log(CheckWords());
I am creating a function that receive the text and check if include the answers(xx and yy), it doesn't matter the order. The ans list, can have 1,2 or more words, it will work.
let ans = ['xx','yy'];
function check(text){
text = text.toLowerCase();
let counter = 0;
ans.forEach((x) => {text.includes(x) && counter++ })
return counter === ans.length
}
console.log(check("aa bb")) // false
console.log(check("xx bb")) // false
console.log(check("aa yy")) // false
console.log(check("xx yy")) // true
console.log(check("yy xx")) // true

loop through array to find matches and return every possible solution

I have a small input field where this code gets activated everytime a key is pressed inside it. But it now only prints "found something" when the name exacly matches what you type in the input field.
How can change a part that when I type something like "b" it already removes the matches where there is no "b" in the name is and print every possible matches that still have a "b".
My small code to find the match.
Info is my json big array where I can loop through all the names with info[i].name
var textInput = $findperson.find('input').val();
console.log(textInput);
for (i = 1; i < info.length; i++) {
if (textInput === info[i].name) {
console.log('found something');
}
}
Set Flag if found any match and print them, otherwise print found nothing,
for gi g mean search globally and i mean ignore case sothat A will match a and vise verse.
var textInput = $findperson.find('input').val();
console.log(textInput);
found = false
for (i = 1; i < info.length; i++) {
if (info[i].name.match(new RegExp(textInput,"gi")) ) {
console.log(info[i].name);
found = true
}
}
if(!found){
console.log("found nothing")
}
I would use regex like this:
var textInput = $findperson.find('input').val();
var regex = new Regexp(".*("+textInput+").*","i");
var filtered = info.filter(function (current) {
return current.name.match(regex);
});
console.log(filtered);
Just use indexOf to search for one String within another:
if(info[i].name.indexOf(textInput) != -1) {
indexOf will return -1 if String isn't found within the other.
You can try searching for some letters in one of the results 'balloon', 'ball', 'apple' in the example below:
var results = ['balloon', 'ball', 'apple'];
function filterResults() {
var input = document.getElementById('input').value;
var resultsFiltered = results.filter(function(a) {
return a.indexOf(input) != -1;
});
var result = ''; resultsFiltered.map(function(a) {
result += a + '<br/>';
}); document.getElementById('result').innerHTML = result;
}
<input id='input' onkeyup='filterResults();'/>
<div id='result'></div>

Seeing if input matches array if not alert

var tagAllowed = true;
var allowedTags =["Person","People","Dance","Word"];
if(tagAllowed === true) {
for(var i=0;i<allowedTags.length;i++){
var aTags = allowedTags[i];
if(input.val().toLowerCase() === aTags.toLowerCase()) {
tagged.append('<span unselectable="on" class="tagged '+colorize+'" title="Click To Delete">'+inputVal.trim()+'</span>');
tagSize = $('.tagged').length;
var ele = $('.tagged').last(),
subtract = parseInt(ele.outerWidth(true),10);
input.width(input.width() - subtract);
tagged.width(tagged.width() + subtract);
input.css('marginLeft','5px');
input.val("");
input.css('color','#000');
} else {
errorMess.children('span').remove();
errorMess.prepend('<span>'+errorProcess+'<span>');
errorMess.slideDown();
}
}
The following code works in a way, if the input.val() does not match it will show the custom alert errorMess and well even if the word matches it still shows the custom alert. I am wondering if maybe I am doing something wrong in my conditional. As I don't need the custom alert to appear if the words match.
If any suggestions please post. I know this isn't the best example with just a code, but I hope all of you get what I am trying to say. I just don't want the custom alert to appear if the two words match together.
You have the if-statement inside the for-loop. The input value will never equal more than one of the tags in the array. You could use a for-loop to set a boolean. Then the if-statement could follow the for-loop.
boolean isAllowedTag = false;
for(var i=0;i<allowedTags.length;i++){
var aTags = allowedTags[i];
if(input.val().toLowerCase() === aTags.toLowerCase()) {
isAllowedTag = true;
break;
}
}
if (isAllowedTag) {
// ...
} else {
errorMess.children('span').remove();
errorMess.prepend('<span>'+errorProcess+'<span>');
errorMess.slideDown();
}
}
add a break; after your input.css('color, '#000'); line. also, you should really change those last 3 lines to: input.val("").css({marginLeft:'5px', color:'#000'});. Making calls to .css() is slow, so it's better to do as much as you can in one call.

Skipping non matching strings when looping through an array in javascript

In the code below I have a form input. When the user searches for a string that happens to be in the array I want it to output the query. When a user happens to search for a string not in the array I want to output an error message. The problem is when a user searches for a string that is other than item [0] in the array (in this case ipsum) they get an error message and then they get their query returned. I want to know if this can be remedied using the code below or if a different methodology for doing this should be pursued ( I know that's an opinion ).
<form>
<input type="text" id="formInput"></input>
<input type = "button" id="search"></input>
</form>
<script>
var search = document.getElementById("search");
var data = ["lorim", "ipsum"];
search.onclick = function(){
var formInput = document.getElementById("formInput").value;
for (i=0; i<data.length; i++){
if (data[i] === formInput) {
alert(data[i]);
}
else{ alert("not working yet"); }
}
};
</script>
you don't need a loop, just use indexOf:
search.onclick = function(){
var formInput = document.getElementById("formInput").value;
if (data.indexOf(formInput) === -1) {
// they entered a bad search term
return;
}
// do the rest of your search logic
};
:) Keep at it.
The thing to remember is that you can only say 'nope didn't find it' after searching everything. So... keep a flag :)
var didntFind = true;
for (var i = 0; i < data.length; i++) {
if (data[i] === formInput) {
alert(data[i]);
didntFind = false;
break;
}
}
if (didntFind) alert('error!');
You can also check if i === data.length-1 after the loop, but the above code should be less confusing for you. Hope this helps

validate 2 dropdowns (only some combinations valid)

I am completely new to JavaScript.
I have size and color dropdowns on a page for users to order a product, but only certain combinations are available i.e. pink is the only color in large sizes.
I thought I'd make an array of allowed sizes and test the user input against these.
If the choice is invalid then I want a popup to tell the user why.
In the real world I'll use SQL & PHP to create the array of allowed choices, in the example below I've hard coded 3 valid choices for testing. Unfortunately the code below doesn't do anything.
I'm sure it's a simple newb mistake. I really don't know what I'm doing :)
Can somebody help me out?
The validation function is supposed to happen when user clicks the form submit...
<form id="form1" name="form1" method="post" onsubmit="return validate_form()"
action="cart.php">
Here's the function:
<script type="text/javascript">
function validate_form() {
var allowed = new Array();
allowed[0]="10,beige";
allowed[1]="10,black";
allowed[2]="10,pink";
var chosenColInd = document.getElementById("colID");
var chosenColText = colID.options[colID.selectedIndex].text;
var chosenSizeInd = document.getElementById("sizeID");
var chosenSizeText = sizeID.options[sizeID.selectedIndex].text;
var chosenSizeCol = chosenSizeText+","+chosenColText;
var found = "false";
for ( var i = 0; i < allowed.length; i++ ) {
if (allowed[i]=chosenSizeCol) {
found = "true";
}
}
if (found = "false") {
alert( 'The variation you have selected is currently unavailable. Please select another.' );
return false;
} else {
return true;
}
}
</script>
There are a few lines where you use the assignment operator (that is single equals =) instead of one of the equality operators (that is double or triple equals, triple is usually preferred in JavaScript). Example:
if (found = "false") {
Would appear to be the problem at first sight - it's an assignment not a comparison :) use triple equals === instead of single:
if(found === "false") {
Also, consider the following (commented) updates to your code, which reflects more the typical style of JavaScript code:
function validate_form() {
//no need to use new Array(), use array literal instead
var allowed = [
"10,beige",
"10,black",
"10,pink"
];
var chosenColInd = document.getElementById("colID");
var chosenColText = colID.options[colID.selectedIndex].text;
var chosenSizeInd = document.getElementById("sizeID");
var chosenSizeText = sizeID.options[sizeID.selectedIndex].text;
var chosenSizeCol = chosenColText+","+chosenSizeText;
var found = "false";
for ( var i = 0; i < allowed.length; i++ ) {
//use equality operator instead of assignment
if (allowed[i]===chosenSizeCol) {
found = true; //may as well use a boolean rather than string
break; //exit loop early, no need to continue if we've already found
}
}
if (!found) { //no need to do a comparison with already boolean values
alert( 'The variation you have selected is currently unavailable. Please select another.' );
}
//may as well just return found here now that we're using a boolean
return found;
}

Categories

Resources