Javascript Array storage - javascript

Good morning;
I've started studying javascript for passion, and I'm really liking it! but I have a question on how to store values in an array. I tried to store 2 email addresses (through regular expression) and display the value stored every time, but I can only store one and the second prompt doesn't even run, can you help me? Thank youuu
var myRE = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var prompt = prompt("Your email addess");
if (myRE.test(prompt)) {
alert("It's OK");
var myArray = [prompt];
alert(myArray[0]);
var prompt1 = prompt("another one");
if (myRE.test(prompt1)) {
alert("It's OK");
myArray.push(prompt1);
alert(myArray[1]);
} else {
alert("Put a fckng mail man");
};
} else {
alert("Put a mail man");
}

The javascript reference to the native browser function prompt is being overwritten by this line:
var prompt = prompt("Your email addess");
(now prompt is equal to the value returned and not the function that displays a window for the user to type in.)
Simply rename your variable to avoid this:
var anyOtherName = prompt("Your email address");
Now, next time you use prompt it will still be the function that displays a window.

Related

How do I store the content of a variable for later use in other function (Javascript)

I have been trying to make a simple Register/Login system in JS. I tried to get the username/password values through user inputs and turn them into variables using a register() function. After that, however, these variables no longer hold any value, and I need them to compare with the new login username/password to check if they match in order to login.
Here's what I tried.
The function below attributes the user's input to the respective variables successfully. The ID's are from a text input in a HTML file.
function register () {
var user1 = window.document.getElementById('username')
var pass1 = window.document.getElementById('password')
alert('User registered, user your credentials to login')
}
When I click the 'register' button in the html page, the function is called (onclick="register()"), and I am redirected to the login page.
Here's the code for the login session:
function login () {
let userL = window.document.getElementById('usernameL')
let passL = window.document.getElementById('passwordL')
if (userL === user1 && passL === pass1) {
alert(`${userL} successfully logged`)
}
else {
alert('Invalid credentials')
}
It doesn't work because in the code above, user1 and pass1 are "not defined", according to the console. How do I keep the values of these variables stored after getting them in the first function(register) in order to use it when the second function(login) is used?
You can use Session storage to store temporary data
sessionStorage.setItem('username',username);
sessionStorage.setItem('password',password);
To retreive the data in login page
var user1 = sessionStorage.getItem('username',username);
var pass1 = sessionStorage.getItem('password',password);
then clear
sessionStorage.clear();
Please refer the below code,
<script>
const allUsers = [];
function register() {
// assuming user1 && pass1 are input elements with ids username, password
var user1 = document.getElementById("username").value;
var pass1 = document.getElementById("password").value;
// TODO: always validate the data that is taken as input from the user
// create an object containing user details
const newUser = {
username: user1,
password: pass1,
};
// push the registered user in allUsers array
allUsers.push(newUser);
alert("User registered, user your credentials to login");
}
function login() {
// assuming user1 && pass1 are input elements with ids usernameL, passwordL
let userL = document.getElementById("usernameL").value;
let passL = document.getElementById("passwordL").value;
// TODO: always validate the data that is taken as input from the user
// loop through allUsers array to check whether we already have a user registered with the details given in login form
for(let user of allUsers) {
if(user.username === userL && user.password === passL) {
alert(`${userL} successfully logged`);
return; // exit the function here
}
}
// if user detail not found in allUsers array this alert will be executed
alert("Invalid credentials");
}
</script>
Store all users in array after successful registration
While login, loop through the registered users array to check whether the user has already registered or not and decide how to handle the logic.
As PM 77-1 mentioned in the comment, please be aware that getElementById(ID) returns us the element itself (the tag itself), if we want to access it text content we can use either getElementById(ID).textContent or getElementById(ID).innerText

Find specific user name of returning user using local storage

I'm trying to detect new visitor on my page, ask for his name using prompt and store it on local storage.
If he is a return user, show his name on the page using 'querySelector'.
I started from checking if it's a new user or not, but I got stuck.
var localStorage = window.localStorage;
if(localStorage.getItem("reutrn_user")) {
//
} else {
var name = prompt("Please enter your name");
localStorage.setItem('username', name);
}
Any idea how to get the username and show it in case he is a return user?
Thanks
Your getItem and setItem have different keys.
In your example, one key is reutrn_user and the other username.
var localStorage = window.localStorage;
if(localStorage.getItem("username")) {
console.log(localStorage.getItem("username"))
} else {
var name = prompt("Please enter your name");
localStorage.setItem('username', name);
}

multi-dimensional javascript array only affecting last array in forEach [duplicate]

This question already has an answer here:
Searching array reports "not found" even though it's found
(1 answer)
Closed 4 years ago.
I have a multi-dimensional array in JavaScript that holds basic Usernames and to-be hashed passwords. At the moment, when the function to check the credentials is called, the forEach will only check the last array.
const titleText = document.getElementById('loginText');
const usernameField = document.getElementById('usernameField');
const passwordField = document.getElementById('passwordField');
const usernames = [['guido','password'],['ben','test']];
function checkCreds() {
titleText.textContent = ">> Checking login";
usernames.forEach(element => {
if (element[0] === usernameField.value) {
if (element[1] === passwordField.value) {
titleText.textContent = '>> Login Valid';
window.location = "dashboard.html";
} else {
titleText.textContent = '>> Password incorrect';
};
} else {
titleText.textContent = '>> Login incorrect';
};
});
};
Here, when I type in the credentials: guido and password, it will say that the login is incorrect. But when I type in ben and test, it will proceed as normal. If anyone has an idea on to why this won't work or has better code, please drop an answer. As I say, this will be hashed, salted and not in the file, all that stuff when it's working.
The problem seems to be that you aren't breaking out of your loop so you are in fact checking all elements in the array but the last element is the one that is sticking. Try braking from your loop, something like this;
const titleText = document.getElementById('loginText');
const usernameField = document.getElementById('usernameField');
const passwordField = document.getElementById('passwordField');
const usernames = [
['guido', 'password'],
['ben', 'test']
];
function checkCreds() {
titleText.textContent = ">> Checking login";
// instead of using Array.forEach use a standard for loop, this allows you to
// break out of the loop and return.
for(let i = 0; i < usernames.length; i++){
if (usernames[i][0] === usernameField.value){
if (usernames[i][1] === passwordField.value){
// show that the login was successful
titleText.textContent = '>> Login Valid';
// redirect to the dashboard
window.location = 'dashboard.html';
// just return here, there is no need to break out of the loop,
// returning will end the execution of this function.
return;
}
}
}
// display the error to the user, we don't want to indicate if the
// password or the username were invalid because that tells an attacker
// they have the correct user name.
// We also don't have to check a flag because a valid login will result
// in this code never being hit
titleText.textContent = '>> Login incorrect';
};
Edit:
Based on the information from Ben West I have updated the solution to use a standard for loop to allow breaking out of the loop.

JavaScript: getting undefined variable message but variable is defined (I think)

I'm relatively new to JavaScript, although I have recently turned a corner. I just wrote this code block to validate an email field that's generated by a CMS, but I'm getting a message that invalidEmailMsg is undefined. I have tried placing the variable declaration inside the function, outside the function, inside the if statement (basically flailing my arms around), but the message persists. Can anyone help? Please and thank you.
var email = document.getElementById("trouble-tickets-email");
email.addEventListener("keyup", function() {
var invalidEmailMsg = document.forms[1].getElementsByClassName("form-error-msg")[3];
var emailValue = email.value;
var emailPattern = /.+#.+\..+/;
if(emailPattern.test(emailValue) === false) {
invalidEmailMsg.css.style("display","block");
invalidEmailMsg.innerHTML = "custom message";
}
});

PhoneGap Userlogin Local storage

I am trying to create a user login application using Phonegap.
here is my code
function successCB(tx) {
var setName = $("#name").val();
var setID = $("#ID").val();
//alert('select * from USER where name='+setID+' and password='+setName+'');
tx.executeSql('select * from USER where name='+setID+' and password='+setName+'', [], querySuccess, errorCB);
}
When I uncomment the alert, it shows the data enter from the text fields, however I cant figure out what to do next,
I want to check the inputs from the database and if user id and password are correct the flow should go to another page like a proper login page.
What is the appropriate way to do that in
function querySuccess(tx, results)
You need to verify that some rows got selected. If the typed in username and password was correct the sql sentense will return a row with that user.
Either you make a global variable called DB where you connection is stored. Then you chould do something like this.
var db = "";
db = window.openDatabase("Database", "1.0", "Cordova Demo", 200000);
// collect your values as you already do.. i just showed em for demontration purpose..
var setName = $("#name").val();
var setID = $("#ID").val();
// execute this code from a function of your choice.
db.transaction(function(con) {
con.executeSql('select * from USER where name='+setID+' and password='+setName+'', [], function (tx, results) {
var len = results.rows.length;
if (len==1) {alert("you logged in with some user");}
});
});
Or with what you posted.
function querySuccess(tx, results) {
var len = results.rows.length;
if (len==1) {alert("you logged in with some user");}
}
So what you need to do after all this is to make sure that you can detect if you are logged in or not. Its not of much use if you have to log in every time u change page or what your app contains. You could use the localstorage to detect that.
You could also make a global variable to hold the value of loggedin or not.
:-)
I hope my code helped you.

Categories

Resources