I'm trying to use window.location.href in a Loop - javascript

I want to redirect a user to a new page if their login details are correct. However, when I use the window.location.href("portal.html") in a simple if statement to check if user details match an already stored data in a variable, it works, but when I use it in a for loop to loop through an array of stored data it doesn't render the the portal.html page.
please help, Thanks.
for(let i = 0; i<= objPeople.length; i++){
if(name === objPeople[i].username && pass === objPeople[i].password){
window.location.href="portal.html"
return
}
} console.log("incorrect login details");

Use find instead of a for loop:
if (objPeople.find(x => x.username === name && x.password === pass))
window.location.href="portal.html"
else
console.log("incorrect login details")
I tested your code and like Adnan Ahmed mentioned it does not work because of the return statement. It should be break.

Try it like this
let matches = false;
for(let i = 0; i<= objPeople.length; i++){
if(name === objPeople[i].username && pass === objPeople[i].password){
matches = true;
}
}
if(matches){
window.location.href="portal.html"
}

Just remove return. return statement prevents the redirection to the new page. I tried following example and it works:
for (let i = 0; i < 20; i++) {
if (i === 10)
window.location.href = "https://google.com";
}

Related

Comparing two arrays in a class with a loop

I am trying to compare two arrays without using any built in 'compare' functions. I'm getting stuck on how to format the loop to run ( the i >= my_arr.length part) because I feel like part of my issue might be there. I keep getting true even when the two arrays are different. This is a function I'm writing inside of a class. Thanks in advance
is_equal(other_arr){
let result=[];
for(let i =0; i >= my_arr.length; i++){
if(MySet[i] === other_arr[i]){
return true;
}else{
return false;
}}}}
I'd change it around slightly like this:
is_equal(other_arr){
if (my_arr.length != MySet.length) return false;
for(let i =0; i >= my_arr.length; i++){
if(MySet[i] !== other_arr[i]){
return false;
}
}
return true;
}
The function you have written returns true on the first equal element contained in the Arrays. Try the code below:
is_equal(other_arr){
let result=[];
for(let i = 0; i < my_arr.length; i++){
if(MySet[i] !== other_arr[i]){
return false;
}
}
// If the 'for loop' is over, all elements are equal, only then is true return
return true;
}

alert() window appears for every element in an array when looping?

I am trying to make some kind of search function, where a pop-up would appear and ask for an input from the customer and then compare it to the array items and return another alert window with either "found" or "not found"
Here is my code for the specific function:
this.searchItem = function(){
var searchInput = window.prompt('Enter the search value:','');
var i;
for (i = 0; i< model.items.length; i++){
if (model.items[i] == searchInput) {
window.prompt("found");
} else {
window.prompt("not found");
}
}
}
It is kind of working. The problem is that it keeps showing a new alert window for every single element in the array. For example if I have 6 elements in the array and only one is matching the search input, then it will show me 5 alert windows with "not found" and one with "found". Another one appears after i close the previous one or if I click the ok button. How do I make it show me the alert window only once to tell me if it found it or not? Thanks!
Put the alert (not prompt) after the loop. Also need to switch to using a variable to track whether or not the item was found:
this.searchItem = function(){
var searchInput = window.prompt('Enter the search value:','');
var i;
var found = false;
for (i = 0; i< model.items.length; i++){
if (model.items[i] == searchInput) {
found = true;
break;
}
}
window.alert(found ? 'found' : 'not found');
}
Instead of showing the alert every time, set a variable such as var found=true. After loop terminates then show alert based on status of that var.
To show alert only once you have to execute the alert after loop ends, not inside loop.
Since you aren't doing anything else in your function after the loop, you can simply return when you find the element you were looking for. And only display the "not found" if you finish the loop without finding the element.
this.searchItem = function(){
var searchInput = window.prompt('Enter the search value:','');
var i;
for (i = 0; i< model.items.length; i++){
if (model.items[i] == searchInput) {
window.alert("found");
return;
}
}
window.alert("not found");
}
You could also simplify this by using Array.prototype.indexOf or Array.prototype.includes
this.searchItem = function(){
var searchInput = window.prompt('Enter the search value:','');
var i;
var found = false;
for (i = 0; i< model.items.length; i++){
if (model.items[i] == searchInput) {
found = true;
}
}
if(found == true)
window.prompt("found");
else
window.prompt("not found")
}
you are telling it to show the message every time it finds one, if you are seeking to finding only 1 match then just terminate the loop when you find it.
End the loop using break; or simply just set i to the arrays length:
......
if (model.items[i] == searchInput) {
window.prompt("found");
return 0;
}
.....
window.prompt("Not found"); //if fucntion doesn't return then it's not found.
OR
var found = false;
......
if (model.items[i] == searchInput) {
window.prompt("found");
found = true;
break;
}
.....
if(!found) window.prompt("Not found");
OR
......
if (model.items[i] == searchInput) {
window.prompt("found");
found = true;
i = items.length;
}
.....
if(!found) window.prompt("Not found");

Javascript, check if input is in array

I am new to javascript and struggling with the use of arrays.
I am trying to check if user input value is in an array I declared called fruits. If it is I want to execute code. If it is not I want an alert displayed. I tried using the
instanceof
method to check the value but the code doesn't execute any of the if else statement. Any ideas as to why?
$("#submit-btn").bind("click", function() {
var comment = $("#comments");
var commentValue = $.trim(comment.val());
var index;
var fruits = ["Banana", "Orange", "Apple", "Mango"];
for (index = 0; index < fruits.length; index++) {
text += fruits[index];
if (commentValue.length === 0) {
alert('Comments are required to continue!');
}
else if (commentValue instanceof fruits){
execute code
});
}
else {
alert('not a valid fruit');
}
return false;
}
});
Your first if should be outside the for loop.
Inside you simply change the else if to
if(commentValue === fruits[index])
And then you move the code inside the else out after the for loop.
A simpler way of doing it would be:
if (commentValue.length === 0) {
alert('Comments are required to continue!');
return false;
}
if(fruits.indexOf(commentValue) > -1) {
execute code
return false;
}
alert('not a valid fruit');
return false;
Try indexOf(), if indexOf return anything bigger then -1, you have match
like this:
else if (commentValue.indexOf(fruits[index]) > -1){

Need Explaination in this word guessing javascript

So, I want to check wether the input that I give is being correctly executed, but why does the if statement always return false even i give the correct input?
I don't want the solution only the need explanation. Please is there anyone who could explain? I've included my html input elements Just in case something wrong with it.
<script>
var text1 = ["O","K","E"];
var text2 = ["_","_","_"];
function guess(j){
for(i=0; i < text1.length; i++){
if(j == text1[i]){
text2[i] = j;
console.log(text2[i])
}
else {
console.log("try again")
}
}
}
</script>
The comment of #Unglückspilz in code:
// extra "K" to show how to handle multiple finds
var text1 = ["O","K","E","K"];
var text2 = ["_","_","_","_"];
function guess(j){
// a flag to set if one or more letters were found
found = false;
// check every letter in the haystack against given needle
for(i=0; i < text1.length; i++){
if(j == text1[i]){
// exchange underbar against found letter(s)
text2[i] = j;
console.log(text2[i]);
// set flag to true
found = true;
}
}
// no letter was correct
if(!found){
console.log("try again");
}
// return boolean if anything was found (but not how many)
return found;
}

jquery indexOf replacement

Here I have a hidden input field
<input type="hidden" value="php,php mysql" id="tags"/>
and I also have a normal input box which users could add their new tags, now I want to check if the new tag which user wants to add is already added for him or not, if it's already added, alert('already there');
here is my code:
var already_added = $('#tags_final').val().toLowerCase();
new_tag = new_tag.toLowerCase();
if (already_added.indexOf(new_tag) < 0){
// add it, everything is OK
}else{
alert('already there');
}
the above works just fine for normal values, for example now if i try to add "php", this is gonna alert('already there'), the problem is, if I add "mysql", this also sends the alert since it finds it in "php mysql", but "mysql" is another tag and it needs to be added. what's solutions come to mind for this?
thanks for your help
I would think you'd want to break this up into separate pieces and perform a full text comparison on the actual tag itself.
var tags = $('#tags_final').val().toLowerCase().split(',');
new_tag = new_tag.toLowerCase();
if ($.inArray(new_tag, tags) < 0) {
// add it
} else {
alert('already there');
}
var tags = $('#tags_final').val().toLowerCase().split(',');
new_tag = new_tag.toLowerCase();
if (tags.indexOf(new_tag) < 0) {
// add it
} else {
alert('already there');
}
Edit: Courtesy of #nybbler, this would be more accurate using the jquery inArray method as linked in his comment.
I think using indexOf directly on the string is faster than either a regex or splitting into an array (even more so when relying on $.inArray).
Simply wrap your already_added string of tags with commas, then do the same for the tag when searching for it with indexOf:
var already_added = ',' + $('#tags_final').val().toLowerCase() + ',';
new_tag = new_tag.toLowerCase();
if (already_added.indexOf(',' + new_tag + ',') < 0) {
// add it
} else {
alert('already there');
}
I got this idea from a similar trick used by jQuery.
Save the tags between braces [php][php mysql]
and search for it
var already_added = $('#tags_final').val().toLowerCase();
new_tag = new_tag.toLowerCase();
if (already_added.indexOf("["+new_tag+"]") < 0){
// add it, everything is OK
}else{
alert('already there');
}
You can use a function like this to look for a key in a comma separated string of keys:
function contains(keys, key) {
var i = 0, k = key.length;
for (var i = 0;(i = keys.indexOf(key, i)) != -1; i += k) {
if ((i == 0 || keys.charAt(i - 1) == ',') && (i + k == keys.length || keys.charAt(i + k) == ',')) {
return true;
}
}
return false;
}
Demo: http://jsfiddle.net/Guffa/UHH9V/

Categories