Skipping non matching strings when looping through an array in javascript - 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

Related

Loop through array to find if the array contains certain names with if statement

I don't use JavaScript much and I know this shouldn't be this difficult. Basically, is what I am trying to do is loop through an array of domain names that I am getting from the users input. ex. [gmail.com, yahoo.com, xyz.com, etc..]. I am using a for loop and if statements to run through it just to check if the array has a certain type of email. So if I am searching for yahoo.com I need to know if there is a gmail.com in there as well.
Here is what I have created so far but I cannot get it to check the second or third or fourth email.
function EmailFunction() {
var emailNames = [fdsg#gmail.com, gjitrerh#yahoo.com, jirg#aol.com];
var emailDomains = [];
var arrEmail = emailNames.split(', ');
var len = arrEmail.length;
for (var i = 0; i < len; i++) {
var domain = arrEmail[i].split("#").pop();
emailDomains.push(domain)
var unique = emailDomains.filter(onlyUnique);
for (var j = 0; j < unique.length; j++) {
if (unique[j] == "yahoo.com") {
var answer = confirm("* Please verify your Email addresses are being sent to the correct personnel.\n\n *** Please press CANCEL to Verify.\n *** Press OK to continue.");
if (answer == true) {
return true;
} else {
return false;
}
} else {
var answer = confirm("* Since you have emails that are not yahoo.COM please retype your emails.\n\n *** Please press CANCEL to Verify.\n *** Press OK to continue.");
if (answer == true) {
return true;
} else {
$('.txbx1').show();
return false;
}
}
}
}
> **Edit:**I edited my question with some temp data.
> I am getting the full email from the user ex. xyz#yahoo.com.
I am then splitting that at the # sign so that I get an
array of emails like = yahoo.com, aol.com, gmail.com.
> I am then need to loop through that
array `unique` to check if the array has a
certain email domain.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Make a set object and define all the domains you wish in it. Then just use has() method in your if statement like that:
if (mySet.has(unique[j])) {
Syntax here

How to check text input changes for certain words?

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

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>

JS: Using Length Property to Write If Statement

I'm very new to JS so go easy on me. I've got this array inside a variable, and am trying to find a better way to write that if statement. So if the names inside that variable grow, I won't need to change the if statement as it won't be hardcoded.
var names = ["beth", "barry", "debbie", "peter"]
if (names[0] && names [1] && names [2] && names [3] {
Do something...
}
Something tells me I need to be using the .length property but I can't work out how to properly use it within that statement. Something along the lines of:
if (names[i] * names.length) {
Do something...
}
I know that's wrong. I think need to be finding the index of each and looping through it makign sure it the loop doesn't exceed the amount of values in the array.
Any help is appreciated. Thanks in advance!
Update: Some users have alerted me that my question might not be as clear. I've setup a CodePen here (http://codepen.io/realph/pen/KjCLd?editors=101) that might explain what I'm trying to achieve.
P.S. How do I stop my from repeating 3 times?
You can use every to test whether every element satisfies some condition:
if (names.every(function (name) { return name })) {
// Do Something
}
every will automatically stop testing when the first non-true element is found, which is potentially a large optimization depending on the size of your array.
Traditionally, you would simply iterate over the array and test each element. You can do so with forEach or a simple for loop. You can perform the same early-termination when you find a non-true element by returning false from the forEach callback.
var allTrue = true;
names.forEach(function (name) {
return allTrue = allTrue && name;
});
if (allTrue) {
// Do something...
}
Please give a english description of what you are trying to accomplish. The below answer assumes you simply want to iterate a list of names and do some processing with each.
You want to use a for loop.
var names = ["beth", "barry", "debbie", "peter"]
for (var i=0; i<names.length; i++) {
// access names[i]
}
The best cross-browser solution is to use a traditional for loop.
var names = ["beth", "barry", "debbie", "peter"],
isValid = true,
i;
for (i = 0; i < names.length; i++) {
isValid = isValid && names[i];
}
if (isValid) {
// do something
}
You can try this;
var checkCondition = true;
for(var i = 0; i<names.length; i++){
if(names[i] !== something) {
checkCondition = false;
break;
}
}
if(checkCondition){
//Do what ever you like if the condition holds
}else{
// Do whatever you like if the condition does NOT holds
}
If i understand right you need something like this
var names = ["beth", "barry", "debbie", "peter"];
var notUndefinedNames = names.filter(function(el){return el !== undefined;});
// if all
if (names.length === notUndefinedNames.length) console.log("You're all here. Great! Sit down and let's begin the class.");
// if one or less
else if (notUndefinedNames.length <= 1) console.log("I can't teach just one person. Class is cancelled.");
else console.log("Welcome " + notUndefinedNames.join(', '));

get the next element with a specific class after a specific element

I have a HTML markup like this:
<p>
<label>Arrive</label>
<input id="from-date1" class="from-date calender" type="text" />
</p>
<p>
<label>Depart</label>
<input id="to-date1" class="to-date calender" type="text" />
</p>
<p>
<label>Arrive</label>
<input id="from-date2" class="from-date calender" type="text" />
</p>
<p>
<label>Depart</label>
<input id="to-date2" class="to-date calender" type="text" />
</p>
I want to get the next element after from dates to get the corresponding to date. (Layout is a little more complex but from date has from-date class and to date has to-date class).
This is I am trying to do, I want to take a from date element and find the next element in the dom with to-date class. I tried this:
$('#from-date1').next('.to-date')
but it is giving me empty jQuery element. I think this is because next gives the next sibling matching the selector. How can I get the corresponding to-date?
Couldn't find a direct way of doing this, so wrote a little recursive algorithm for this.
Demo: http://jsfiddle.net/sHGDP/
nextInDOM() function takes 2 arguments namely the element to start looking from and the selector to match.
instead of
$('#from-date1').next('.to-date')
you can use:
nextInDOM('.to-date', $('#from-date1'))
Code
function nextInDOM(_selector, _subject) {
var next = getNext(_subject);
while(next.length != 0) {
var found = searchFor(_selector, next);
if(found != null) return found;
next = getNext(next);
}
return null;
}
function getNext(_subject) {
if(_subject.next().length > 0) return _subject.next();
return getNext(_subject.parent());
}
function searchFor(_selector, _subject) {
if(_subject.is(_selector)) return _subject;
else {
var found = null;
_subject.children().each(function() {
found = searchFor(_selector, $(this));
if(found != null) return false;
});
return found;
}
return null; // will/should never get here
}
.next('.to-date') does not return anything, because you have an additional p in between
You need .parent().next().find('.to-date').
You might have to adjust this if your dom is more complicated than your example. But essentially it boils down to something like this:
$(".from-date").each(function(){
// for each "from-date" input
console.log($(this));
// find the according "to-date" input
console.log($(this).parent().next().find(".to-date"));
});
edit: It's much better and faster to just look for the ID. The following code searches all from-dates and gets the according to-dates:
function getDeparture(el){
var toId = "#to-date"+el.attr("id").replace("from-date","");
//do something with the value here
console.log($(toId).val());
}
var id = "#from-date",
i = 0;
while($(id+(++i)).length){
getDeparture($(id+i));
}
Take a look at the example.
try
var flag = false;
var requiredElement = null;
$.each($("*"),function(i,obj){
if(!flag){
if($(obj).attr("id")=="from-date1"){
flag = true;
}
}
else{
if($(obj).hasClass("to-date")){
requiredElement = obj;
return false;
}
}
});
var item_html = document.getElementById('from-date1');
var str_number = item_html.attributes.getNamedItem("id").value;
// Get id's value.
var data_number = showIntFromString(str_number);
// Get to-date this class
// Select by JQ. $('.to-date'+data_number)
console.log('to-date'+data_number);
function showIntFromString(text){
var num_g = text.match(/\d+/);
if(num_g != null){
console.log("Your number:"+num_g[0]);
var num = num_g[0];
return num;
}else{
return;
}
}
Use JS. to get the key number from your id. Analysis it than output the number. Use JQ. selecter combine string with you want than + this number. Hope this can help you too.
I know this is an old question, but I figured I'd add a jQuery free alternate solution :)
I tried to keep the code simple by avoiding traversing the DOM.
let inputArray = document.querySelectorAll(".calender");
function nextInput(currentInput, inputClass) {
for (i = 0; i < inputArray.length - 1; i++) {
if(currentInput == inputArray[i]) {
for (j = 1; j < inputArray.length - i; j++) {
//Check if the next element exists and if it has the desired class
if(inputArray[i + j] && (inputArray[i + j].className == inputClass)) {
return inputArray[i + j];
break;
}
}
}
}
}
let currentInput = document.getElementById('from-date1');
console.log(nextInput(currentInput, 'to-date calender'));
If you know that the to date will always be the next input element with a class of "calender", then you don't need the second loop.

Categories

Resources