Users = new Array;
Passwords = new Array;
function LogIn() {
Users[10] = "username"
Passwords[10] = "password"
Username = user.value;
Password = pass.value;
for (i = 0; i <= Users.length; i++) {
if (Users[i] == Username) {
if (Passwords[i] == Password) {
alert("yay!");
} else
{
alert("nay");
}
}
}
}
function Register() {
Username = user.value;
Password = pass.value;
Users.push(Username);
Passwords.push(Password);
}
Alright, so I'm teaching myself Javasctipt in my free time and I decided that the best way would be to just mess around with it for a while. I am trying, currently, to build a primative "log in"/"register" webpage/function and I've obviously run into a few problems.
Global variables. I need the arrays "Users" and "Passwords" to be global, but the way I have it set up now, I think they are initialized every single time I call the function-set. So, I guess I'll ask both my questions like this: I realize that arrays probably aren't the best thing for a project like this, however, how do I get the values I store in the arrays to persist from run to run?
<script type="text/javascript" src="LogIn.js"></script>
<script type="text/javascript" src="Register.js"></script>
<body>
Username: <input type="text" id="user" />
Password: <input type="password" id="pass" />
<input type="button" value="Log In" onClick="LogIn()"/>
<input type="button" value="Register" onClick="Register()" />
<hr />
</body>
It was kind of difficult to understand what you're asking for, but I think this will point you in the right direction:
Users = new Array;
Passwords = new Array;
Users[0] = "john";
Users[1] = "sue";
Users[2] = "jack";
Passwords[0] = "blue";
Passwords[1] = "black";
Passwords[2] = "green";
function LogIn() {
//login logic here
}
pretty close
Users = new Array();
Passwords = new Array();
function LogIn() {
Username = document.getElementById("user").value;
Password = document.getElementById("pass").value;
for (i = 0; i <= Users.length; i++) {
if (Users[i] == Username) {
if (Passwords[i] == Password) {
alert("yay!");
} else
{
alert("nay");
}
}
}
}
function Register() {
Username = document.getElementById("user").value;
Password = document.getElementById("pass").value;
Users.push(Username);
Passwords.push(Password);
}
just need a little tweaking.
This question is a bit hard to understand. Web pages are stateless and values stored in javascript will only persist until the page is reloaded.
For your experiment, if you wanted to do some type of persistence across page loads you should look at something like using cookies.
Related
I'm sure I'm missing something obvious here but I've had a really good look over this, combing for typos and such but I can't see what the problem is. I want this to be a simple form that requires a username/password combination to validate. The usernames/passwords having to match hasn't been implemented yet because my initial testing can't get over this first hurdle of the form always validating!
I've definitely made a solid go at it and I feel bad I'm getting stuck here, even looking over tons of references and comparing them to my own. I'm not even sure if the event listener itself is the problem or if the problem comes from poor coding in the function. Opening console in browser shows me no errors either. Could anybody point out where my issue is? Thanks.
"use strict";
let loginform = document.forms.login;
loginform.addEventListener("submit", checkLogin);
let users = [];
let pwords = [];
users = ["Administrator", "Manager", "Cleric", "Scribe"];
pwords = ["Password01", "Password", "Admin", "P#ssword"];
//*** NOTE: the password for each username is specific. Use the the alignment of the data in the table above (i.e. the password for the Administrator account is Password01, etc.). ***
function checkLogin() {
var usernameInput = loginform.getElementById("Username").value;
var pwInput = loginform.getElementById("Password").value;
//.includes is what we need for the array checking if statements
//For Loop 1
for (usernameInput in users) {
if (!users.includes(usernameInput)) {
window.event.preventDefault();
alert("Your username is incorrect. Please try again.")
loginform.user.focus();
return false;
} else {
//For Loop 2
for (pwInput in pwords) {
if (!pwords.includes(pwInput)) {
window.event.preventDefault();
alert("Your password is incorrect. Please try again.")
loginform.pword.focus();
return false;
}
}
}
}
}
<h1 id="main">Login to Umbrella Corporation</h1>
<div id="container">
<form name="login" action="success.html" method="POST">
<input type="text" name="user" id="Username">
<br>
<br>
<input type="password" name="pword" id="Password">
<br>
<br>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
</div>
The form element does not have a getElementById.
Change to one of these
var usernameInput = loginform.user.value;
var pwInput = loginform.pword.value;
var usernameInput = loginform.querySelector("#Username").value;
var pwInput = loginform.querySelector("#Password").value;
var usernameInput = document.getElementById("Username").value;
var pwInput = document.getElementById("Password").value;
You do NOT need to loop and then use includes
if (!users.includes(usernameInput))
is enough
Here is an optimised test
function checkLogin(e) { // event is available here
const usernameInput = loginform.user.value;
const pwInput = loginform.pword.value;
if (!users.includes(usernameInput)) {
e.preventDefault();
alert("Your username is incorrect. Please try again.")
loginform.user.focus();
return false;
} / no need for else after a return
if (!pwords.includes(pwInput)) {
e.preventDefault();
alert("Your password is incorrect. Please try again.")
loginform.pword.focus();
}
}
I think the problem here is that you're trying to loop through your data using the input provided:
var usernameInput = loginform.getElementById("Username").value;
for (usernameInput in users) {...}
This won't work. What you can do is find if the username that the user has provided is present in the array.
var usernameInput = loginform.getElementById("Username").value;
const userIndex = users.indexOf(usernameInput);
If a user is found, it will return a valid index, else it'll return a -1. You can use this to throw an error to the user.
You can do the same with the password:
var pwInput = loginform.getElementById("Password").value;
const pwIndex = pwords.indexOf(pwInput);
At the final check, you can compare the two indices. If they are equal, they are the right combo, else it's an incorrect username/password combo.
if(pwIndex === userIndex && pwIndex !== -1){...} // Success
else {...} // Failure
Finally, this is how your JavaScript should look like:
function checkLogin() {
var usernameInput = loginform.getElementById("Username").value;
var pwInput = loginform.getElementById("Password").value;
//.includes is what we need for the array checking if statements
const userIndex = users.indexOf(usernameInput);
const pwIndex = pwords.indexOf(pwInput);
if(userIndex === -1 || pwIndex === -1) {
alert("Your username/password is incorrect"); // Always better to provide a generic error. You don't want malicious users to know which part they're getting wrong.
}
}
I am creating a login/signup form for my html blog website. I've managed to create the user information using localStorage or sessionStorage. I would store it whenever someone creates an account, and get it whenever someone wants to log in.
I haven't made the sign out or actual user page yet, but that is not my problem. The problem is that it is too easy for someone to steal passwords or clear all the account data using localStorage.clear()
Here is an HTML example:
<html>
<head>
<script src="index.js"></script>
<link rel="stylesheet" href="style.css">
<title>Accounts</title>
</head>
<body>
<article>
<h1>Log In</h1>
<input type="text" id="signin-username" placeholder="Username" value="">
<input type="password" id="signin-password" placeholder="Password" value="">
<button type="submit" onclick="signin()">Sign In</button>
<!------------------------------------>
<h1>Create Account</h1>
<input type="text" id="create-username" placeholder="Username" value="">
<input type="password" id="create-password" placeholder="Password" value="">
<button type="submit" onclick="create()">Create Account</button>
</article>
</body>
</html>
And here is the javascript for it:
var a = localStorage.length;
function signin() {
var name = document.getElementById('signin-username').value;
var pass = document.getElementById('signin-password').value;
if (name === '' && pass === '') {
console.log('Please provide your account details')
}
else if (name === '') {
console.log('Please provide your username!');
}
else if (pass === '') {
console.log('Please provide your password!');
}
else {
var ii;
for (ii = 0; ii < a; ii++) {
if (name === localStorage.key(ii)) {
console.log('Logged in as ' + name);
ii > a
}
else {
console.log('Account Does Not Exist!')
}
}
}
};
function create() {
var username = document.getElementById('create-username').value;
var password = document.getElementById('create-password').value;
if (username === '' && password === '') {
console.log('Invalid Username and Password')
}
else if (username === '') {
console.log('Invalid Username');
}
else if (password === '') {
console.log('Invalid Password');
}
else {
var i;
for (i = 0; i < a; i++) {
if (username === localStorage.key(i)) {
console.log('Username Exists!');
}
else {
localStorage.setItem(username, password)
}
};
}
}
I had to post The Full thing in order for it to make sense.
Anyone have suggestions, like user cookies, for storing data?
You can even redirect me to a login example!
I've managed to create the user information using localStorage or sessionStorage.
LocalStorage is "local" to the web browser. Data stored in LocalStorage is not shared with the web server, or with other web browsers viewing the site. It makes no sense to store account data in these locations, because doing so will result in an "account" that only exists on one computer.
(SessionStorage works similarly, except it disappears when the browser is closed -- so it's even less useful for your purposes.)
If you want to allow users to create accounts on your web site, you will need some sort of code running on the web server to implement these accounts. There is no way to implement this functionality entirely in client-side Javascript.
I use the following code to validate a password in a form. If the password is correct - Move the user to site X. If it's incorrect (after 3 tries), move the user to site Y.
For some reason, it works only for site Y.
My code:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form>
Enter password to continue: <br>
<input type="text" id="user"/>
<input type="button" id="myButton" value="Enter site"/>
</form>
<script>
let tries = 0;
let error = 0;
let password = 'tiesto';
document.querySelector("#myButton").onclick = ()=> {
let passwordValue = document.querySelector('#user').value;
if (password === passwordValue) {
window.location.href = 'http://maariv.co.il';
} else {
tries++;
alert('Try again please.');
}
if (tries === 3) { // 3 is the border.
error++;
}
if (error === 1) {
window.location.href = 'http://microsoft.com';
}
};
</script>
</body>
</html>
I tried doing:
Checking for syntax errors all over the code.
Changing === to == (I thought, maybe due to it being a string, the quote marks counted as well, of course I was mistaken).
window.location.href = 'http://maariv.co.il', true;
Adding return false right under window.location.href
As a beginner I ask, why would the condition works only in a half? That is, the positive part (than) doesn't work but the negative part (else) does work.
Update:
This is just an exercise. Indeed. This isn't going to production. In production I should store and request the password from a database.
Put the following line let passwordValue = document.querySelector('#user').value; inside onclick of "mybutton".
let tries = 0;
let error = 0;
let password = 'tiesto';
document.querySelector("#myButton").onclick = ()=> {
let passwordInput = document.querySelector('#passwordInput').value;
if (password === passwordValue) {
window.location.href = 'http://maariv.co.il';
} else {
tries++;
alert('Try again please.');
}
if (tries === 3) { // 3 is the border.
error++;
}
if (error === 1) {
window.location.href = 'http://microsoft.com';
}
};
<form>
Enter password to continue: <br>
<input type="text" id="user" />
<input type="button" id="myButton" value="Enter site" />
</form>
Use return :
if (password === passwordValue) {
return window.location.href = 'http://maariv.co.il';
}
Otherwise, the function will execute to the end, and you will reach the second redirection, that will then override the first one.
I've been researching for hours and asked a number of times in stack overflow, but the answers did not help or I don't understand at all (user made use of jquery and php as part of solution which I do not know how to use)
Here are my codes (currentuser-will only show when user is logged in)
var currentUser=userList;
document.addEventListener("DOMContentLoaded",loadUserData);
function loadUserData() {
currentUser = localStorage.getItem("currentUser");
if(currentUser!=null) {
currentUser = JSON.parse(currentUser);
document.getElementById('username').value = currentUser.username;
document.getElementById('name').value = currentUser.name;
document.getElementById('password').value = currentUser.password;
document.getElementById('email').value = currentUser.email;
console.log(currentUser.username);
console.log(currentUser.name);
console.log(currentUser.password);
console.log(currentUser.email);
}
}
My codes to add users as objects into an array when they sign up for an account:
var userList;
document.addEventListener("DOMContentLoaded", loadUserList);
function loadUserList(){
if(localStorage.getItem("userList")===null) {
userList = [] ;
} else {
userList = JSON.parse(localStorage.getItem('userList'));
}
}
function saveUserToStorage(){
var u=document.getElementById("username").value;
var n=document.getElementById("name").value;
var p=document.getElementById("password").value;
var e=document.getElementById("email").value;
var user={"username":u,"name":n,"password":p,"email":e};
localStorage["user"]=JSON.stringify(user);
userList.push(user);
localStorage.setItem('userList',JSON.stringify(userList));
}
When I log in, it would direct me to the edit profile page and display data in the form which the user had entered when signing up.
What I NEED right now is just to change the local storage data by filling in the form. Just like editing it through the Inspect Element, just that it's being edited through the edit profile form. How do i achieve this?
Please help me. Would appreciate solutions without jquery/php
Sample of local storage:
Before editing
{"username":"alice66","name":"alice tan","password":"123","email":"abc#mail.com"}
After editing (through edit profile page)
{"username":"ben66","name":"ben ong","password":"qwerty","email":"xyz#mail.com"}
What would be the correct function to do so?
I tried the following function but it did not work:
var updatedUser=currentUser;
document.addEventListener("DOMContentLoaded",saveChanges);
function saveChanges() {
updatedUser = localStorage.getItem("updatedUser");
updatedUser = JSON.parse(updatedUser);
var u = document.getElementById("username").value = updatedUser.username;
var n = document.getElementById("name").value = updatedUser.name;
var p1 = document.getElementById("password1").value = updatedUSer.password1;
var p2 = document.getElementById("password2").value = updatedUser.password2;
var e = document.getElementById("email").value = updatedUser.email;
updatedUser={"username":u,"name":n,"password1":p1,"password2":p2,"email":e};
updatedUser.push(updatedUser);
localStorage.setItem('updatedUser',JSON.stringify(updatedUser));
}
It is rather simple
https://jsfiddle.net/ft3ur0cw/5/
<input placeholder="name" id="name"><br/>
<input placeholder="nausernameme" id="username"><br/>
<input placeholder="password" id="password"><br/>
<input placeholder="email" id="email"><br/><br/>
<button id="save" >save</button>
<br/><br/>
<input placeholder="name_saved" id="name_saved"><br/>
<input placeholder="nausernameme_saved" id="username_saved"><br/>
<input placeholder="password_saved" id="password_saved"><br/>
<input placeholder="email_saved" id="email_saved"><br/><br/>
function load_user(){
var userdata = localStorage.getItem("userdata");
if(typeof userdata === undefined || userdata === null){
userdata = JSON.stringify({username:"",name:"",password:"",email:""});
localStorage.setItem("userdata",userdata);
}
return JSON.parse(userdata);
}
function save_user(username , name, password, email){
userdata = JSON.stringify({username:username,name:name,password:password,email:email});
localStorage.setItem("userdata",userdata);
return userdata;
}
document.getElementById('save').addEventListener("click",function(){
save_user(
document.getElementById('username').value,
document.getElementById('name').value,
document.getElementById('password').value,
document.getElementById('email').value
);
userdata = load_user();
document.getElementById('username_saved').value = userdata.username;
document.getElementById('name_saved').value = userdata.name;
document.getElementById('password_saved').value = userdata.password;
document.getElementById('email_saved').value = userdata.email;
});
userdata = load_user();
document.getElementById('username_saved').value = userdata.username;
document.getElementById('name_saved').value = userdata.name;
document.getElementById('password_saved').value = userdata.password;
document.getElementById('email_saved').value = userdata.email;
this is pretty much how it goes.
EDIT:
better example demonstrating the use of the functions
I have two files: xml_database.xml and login.html. This is my HTML in login.html:
<h2>Login:</h2>
Username: <input type="text" id="login_username"> <input type="button" value="Sign in!" id="sign_in"><br><br><hr>
<h2>Create an account:</h2>
Username: <input type="text" id="create_username"><br><br>
Welcome text: <textarea id="create_welcome" style="vertical-align: text-top;"></textarea>
<br><br>
<input type="button" value="Create an account!" id="create_account">
And in my xml_database.xml:
<?xml version="1.0" encoding="utf-8"?>
<user username="chris97ong" welcomeText="htrftfd"></user>
So when I click on the button to login in login.html, if "chris97ong" is in the username text input, I want to have an alert saying "htrftfd". This is my Javascript for login.html:
document.getElementById("sign_in").onclick = function() {
xmlDoc = loadXMLDoc("xml_database.xml");
users = xmlDoc.getElementsByTagName("user");
var username = document.getElementById("login_username").value;
var bool = false;
for(var i = 0; i < users.length && bool == false; i++) {
if(users[i].getAttribute("username") == username) {
bool = true;
alert("Your welcome text is " + users[i].getAttribute("welcomeText"));
}
}
if(bool == false) { alert("Such username does not exist"); }
}
And it worked perfectly.
Now I want to be able to create an account with the second section. When the button to create an account is clicked, I want to create a node in xml_database.xml "<user>". I want the "username" attribute of this new element to be what is in the text input (with id "create_username") and the "welcomeText" of this new element to be what is in the textarea (with id "create_welcome").
This is what I have tried:
document.getElementById("create_account").onclick = function() {
xmlDoc = loadXMLDoc("xml_database.xml");
users = xmlDoc.getElementsByTagName("user");
var username = document.getElementById("create_username").value;
var bool = false;
for(var i = 0; i < users.length && bool == false; i++) {
if(users[i].getAttribute("username") == username) {
bool = true;
alert("Such username already exists");
}
}
if(bool == false) {
var welcomeText = document.getElementById("create_welcome").value;
new_user = xmlDoc.createElement("user");
new_user.setAttribute("username",username);
new_user.setAttribute("welcomeText",welcomeText);
alert("Account created");
}
}
But it does not work. When I try to login with this new username, the alert states that such a username does not exist. There were no error messages whatsoever and the xml file was not changed at all. What is wrong with my code that I didn't realise? Thx.
PS: I have this in my <head> tag:
<script src="http://www.w3schools.com/dom/loadxmldoc.js"></script>
The createElement method create element on DOM model build from xml loaded on to browser as you know, so this method does not offer access to read and write local files.
Using server side programs such as PHP will be suitable for this solution.