Constructor object name - javascript - javascript

function Account(password, email)
{
this.password=password;
this.email=email;
}
function createAccount()
{
var username="Moshiko22";
var password="1112"
var email="moshiko#walla.co.il";
username=new Account(password, email);
}
The first function is a constructor. Assuming 'username', 'password' are user entered, I want to create an account object with the name the USER entered. (as in the object would be the 'username' the user has entered).
I know why what I've done doesn't work, but I don't know how to actually get it done.
Thanks in advance!
Sorry for being unclear: the user enters username, password and email. the password and email are just 2 properties in the object 'Account'. The username is what I want as the object itself.

Sounds like you want an object with the keys being the username?
var users = {};
function createAccount()
{
var username="Moshiko22";
var password="1112"
var email="moshiko#walla.co.il";
users[username] = new Account(password, email);
}

Like this:
function Account(password, email)
{
this.constructor = function (password, email) {
this.password=password;
this.email=email;
}.apply(this, arguments);
}
And then :
var account = new Account("mypwd", "myusername#mydomain.com");

Related

pull out data from array in localStorage

I have a function that takes data from an input and saves it as data in an array during registration. Now I want another function to check during login if the data exists and if it matches. How can I do this using javascript only?
In short, I need a function that checks if the data entered by the user exists and if so, logs him in.
function saveData() {
let name, email, password;
name = document.getElementById("username").value;
email = document.getElementById("email").value;
password = document.getElementById("password").value;
let user_records = new Array();
user_records = JSON.parse(localStorage.getItem("users"))
? JSON.parse(localStorage.getItem("users"))
: [];
if (
user_records.some((v) => {
return v.email == email;
})
) {
alert("Email wykorzystany");
} else {
user_records.push({
name: name,
email: email,
password: password,
});
localStorage.setItem("users", JSON.stringify(user_records));
}
}
I know that this is not how registration should be done. I am just doing it to learn new things.
this is a basic login, when you verify that the emmail and password are right, you can do wathever you want
function checkData() {
const name = document.getElementById('username').value;
const password = document.getElementById('password').value;
let user_records = JSON.parse(localStorage.getItem('users')) || [];
if (
user_records.find((user) => {
return user.name == name && user.password == password;
})
) {
alert('Logged in');
// do your things here
} else {
alert('wrong email or password');
// do your things here
}
}
<input id="username" />
<input id="password" />
<input type="submit" value="submit" onClick="checkData()" />
Extra:
This is a thing that you can do only for learning purpose, wich is to add a key to the local storage, for example: localStorage.setItem('loggedIn', true) and set in every page a check for this value, if is true show the page, if is false redirect to login. In the real world we use JWT tokens that contains all the information about the user etc... You can search for JWT token authentication on google and learn that, wich is really usefull in the front-end world
function saveAndTestUser() {
// here use const as they are not updated
const name = document.getElementById("username").value;
const email = document.getElementById("email").value;
const password = document.getElementById("password").value;
// Get all the records of the users
// prefer camelcase : not a rule though but it's better this way
const storedUsers = localStorage.getItem('users')
// if there are no stored users then assign empty array
// so that we don't get unexpected errors
const userRecords = storedUsers ? JSON.parse(storedUsers): []
// Checking if email already exists
if(userRecords.some(user => user.email === email)){
alert("user already exists")
return false; // stops the function execution
}
// If email doesn't exists then the code below will be executed
// Similar to if-else
// Add current record to existing records
const newRecords = [...storedUsers, {name, email, password}]
// Set the new record to storage
localStorage.setItem("users", JSON.stringify(newRecords));
}

How to run a javascript function that checks if a username is available

I'm building a javascript function that receives an input and checks it against stored objects in an array to see if it matches against any
The if else statement don't work
const accounts = []; //holds all user name and password
function getinput() {
let pass = document.getElementById("password").value;
let user = document.getElementById("username").value;
let newuser = {
username: user,
password: pass,
};
let match = (toMatch) => toMatch === newuser.username
if (accounts.some(match) === true) {
return alert("choose another `username");
}
accounts.push(newuser)
return alert("account created")
};
var clik = document.getElementById("login").addEventListener("click", getinput);
It should tell the user if a username is available or not
The direct answer to your question would be along the lines of:
function getInput() {
/* store the value of the input */
var current_userName = document.getElementById("username").value;
/* check if that value already exists in the accounts Array */
var matched = accounts.find(account => account.username === current_userName);
/* conditional for each of the two cases */
if (!matched) {
/* code if username is available */
} else {
/* code if username is NOT available */
}
};
document.getElementById("login").addEventListener("click" , getInput);
You have some mistakes in your code, which need fixing.
Also, look into Array.prototype.find() for more info.
Hope this will help you get started in the right direction. Best of luck!
Finally understood what I was doing wrong had to point toMatch of accounts to check for username contained within the array of object
const = [ ]; //holds all user name and password
function getinput() {
let pass = document.getElementById("password").value;
let user = document.getElementById("username").value;
let newuser = {
username: user,
password: pass,
};
//this was where I got it wrong I was doing toMatch === newuser.username which was wrong
let match = (toMatch) => toMatch.username === user
if (accounts.some(match) === true) {
return alert("choose another username");
}
accounts.push(newuser)
return alert("account created")
};
document.getElementById("login

Stuck! Need to create a class with a method then create 4 properties

Come up with the error:
Failed tests
Should contain properties: email, username, password, and checkPassword
Expected undefined to be 'Frank'.
Watched a couple of videos looked it up on W3Schools and MDN and nothing is clicking. Input appreciated.
function ClassTwo(name, pw, mail){
// Exercise Two: Now that you have created your own class,
// you will create a class with a method on it.
// In this class create 4 properties: username, password, email, and checkPassword.
// Set the value of username to name,
// Set the value of password to pw,
// Set the value of email to mail
// Set the value of checkPassword to a function.
// The checkPassword function takes a string as it's only argument.
// Using the 'this' keyword check to see if the password on the class is the same as
// the string being passed in as the parameter. Return true or false.
}
function User (username, password, email, checkPassword) {
this.username = name; // My Code
this.password = pw; // My Code
this.email = mail; // My Code
this.checkPassword = checkPass; // My Code
this.checkPassword = function(abc123){ // My Code
return this.checkPassword; // My Code
}
}
You're not using the right argument names when assigning property values in the User function. Also, 'checkPassword' doesn't have to be passed as the 4th argument. It should be:
function User (username, password, email) {
this.username = username;
this.password = password;
this.email = email;
this.checkPassword = function(string) {
return this.password == string;
}
}
This way we're passing the same number of arguments to the function (like in 'function ClassTwo(name, pw, mail)'.
Alternatively, following the prototype approach, you can create a method:
User.prototype.checkPassword = function(string) {
return this.password == string;
}
It will return true if the argument string is the same as the declared password and false otherwise.
Also, the more modern way of doing the above would be:
class User {
constructor(username, password, email) {
this.username = username;
this.password = password;
this.email = email;
}
checkPassword(string) {
return this.password == string;
}
}

Firebase does multiple calls even with if/else statement JS

I am building an app with Vue and also Firebase. I am new to Firebase and i've some problems with it. I try to store names + emails in the database. What I want is to check first if the email is already in the database and if not, run another function that will store the name + email. If the email is stored in the database I would like to output an alert and cancel the submit.
So the check of the email in the database is going quite well, it will output an alert, and also I am able to retrieve the data. But where the problem lays is that when I enter an email that is not in the database. When I enter a new email (and name) it will check the database and return false but then right away does another call (I dont know why, that's the problem I guess) and it will return true, and the alert of already being there, at the same time. Then it will proceed to another function to store the data because that was the output of the first call (which was false).
My JS code:
checkForm() {
let app = this;
if (this.name == '' || this.emailadress == '') {
alert('You have to fill out the form');
} else {
app.getFirebase();
}
},
getFirebase() {
let app = this;
var ref = firebase.database().ref().child('/aanmeldingen/');
ref.on('value', function(snapshot) {
const array = [];
snapshot.forEach(function(childSnapshot) {
var checkEmail = childSnapshot.val().email;
array.push(checkEmail);
});
const res = array.includes(app.emailadress);
console.log(array);
console.log(res);
if(res) {
alert('You already have entered the giveaway');
} else if (res == false) {
app.store();
}
});
},
store() {
this.step_two = false;
this.active_two = false;
this.active_three = true;
this.step_three = true;
let app = this;
firebase.database().ref('/aanmeldingen/').push({
username: app.name,
email: app.emailadress,
});
}
Screenshot of console (entered Jane, not in the database)
You should be using once() instead of on(). on() leaves the listener attached, so when you push data in store() the listener fires again.

Stored value generating [object HTMLInputElement]

I have an indexedDB and using it for a login function. I'm trying to populate a form with the users information when they log in. However the form populates with [object HTMLInputElement] instead of the users info.
This is where I take the user (db key) to access the Object (the user)
EDITThis is my site where it's running: http://www3.carleton.ca/clubs/sissa/html5/admin.html
My site editor is updating it as I save, so there may be changes to the site script as I try new things.
This is where I take the user (db key) to access the Object (the user)
function loginCheck(user,pass){ db.transaction("users").objectStore("users").get(user).onsuccess = function(event) {
var loggedUser = event.target.result;
if(!loggedUser){
alert('Sorry, Username does not exist. Please try again.');
}else if(pass !== loggedUser.pw ){
alert('Incorrect log in combination. Please try again.');
}else{loggedIn(loggedUser);}
}
}
function loggedIn(loggedUser){
var u=loggedUser;
alert('Welcome '+u.fn+' '+u.ln+' to Macroplay');
//function to populate fields
alert('get values called');
getValues(u);
//session store
var signedin = 'user';
var username = u.userName;
newLocal(signedin,username);
alert('local storage set');
}
I use this function getValues to store the various fields I want from the object.
EDIT: I declared the variable test as global and stored the users first name (fn). The alerts show the correct name but the populate still gives me undefined.
var test;
function getValues(loggedUser){
var u = loggedUser;
alert('storing first name');
test = u.fn;
alert('First name = '+test);
lName = u.ln;
users = u.userName;
pass = u.pw;
email = u.em;
dob = u.dob;
tel = u.tel;
bio = u.bio;
school = u.scl;
alert('user values stored');
if(u.gender == 'M'){
gender[0].checked= true ;
}else{gender[1].checked= true ;}
}
This is the function I use to populate the form that's giving me [object HTMLInputElement]
function populateFields(){
alert('Name of populated field: '+test);
fName.value = test;
lName.value = lName;
users.value = users;
pass.value = pass;
email.value = email;
dob.value = dob;
tel.value = tel;
bio.value = bio;
terms.disabled = true;
school.value = school;
alert('populate fields done');
save.value = 'Update';
signin.innerHTML = 'Log Out';
registerLabel.innerHTML = 'Account Information';
//open user info form
var accountInfo = document.getElementsByTagName('details');
accountInfo[1].open = open;
}
Just look at one line:
fName.value = fName
You are setting the value property of fName to fName itself.
Rather than creating numerous global variables, just use loggedUser directly in populateFields():
fName.value = loggedUser.fn;
Edit: Looking at your site, I see the important bit you left out. populateFields() is being called after the page reloads. So, populateFields() does not have access to any variable created before the page reloaded.
Since I'm helping you with homework, I don't want to just hand you the answer on a silver platter. The trick is that the user data must be retrieved from the database and made available to populateFields() before it is called, or from within the function. You can make the user object available as a global variable, but it may be better to pass it in as a parameter.
You probably want to also cancel the form submission:
document.getElementById("loginForm").onsubmit = function (e) {
e.preventDefault();
}
And then just call populateFields() directly from loggedIn() instead of getValues().

Categories

Resources