How to edit and update data in local storage? - javascript

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

Related

JavaScript - Form validation, want username/password validation but it submits with no issues

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.
}
}

How can i add or update products and prices in my list?

Pretty new to javascript, i want to add and update my list but it doesn't work.
I tried adding following code but it didn't work
Product.prototype.addProduct = function() {
var elol = document.getElementById("lijst");
var nieuwNaam = document.createElement("li");
nieuwNaam.textContent= this.naam;
elol.appendChild(nieuwNaam);
var nieuwPrijs = document.createElement("li");
nieuwPrijs.textContent= this.prijs;
elol.appendChild(nieuwPrijs);
}
Product.prototype.getProducten = function() {
return this.naam + "(€ " + this.prijs +")";
}
This is the document i want wish would work propperly
<!DOCTYPE html>
<html>
<head>
<script src="oefwinkel.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function() {
winkel.addProduct("Potlood", 10);
VulLijst();
var elBtn = document.getElementById("btn");
elBtn.onclick = VoegProductToe;
});
function VulLijst() {
var elol = document.getElementById("lijst");
var producten = winkel.getProducten("</li><li>");
if (producten.length > 0) {
elol.innerHTML = "<li>" + producten + "</li>";
} else {
elol.innerHTML = "";
}
}
function VoegProductToe() {
var naam = document.getElementById("txtNaam").value;
var prijs = document.getElementById("txtPrijs").value;
winkel.addProduct(naam, prijs);
VulLijst();
}
function Product(naam, prijs) {
this.naam = naam;
this.prijs = prijs;
}
</script>
</head>
<body>
<div><label for="txtNaam">Naam:</label>
<input type="text" id="txtNaam" /></div>
<div><label for="txtPrijs">Prijs:</label>
<input type="number" id="txtPrijs" /></div>
<input type="button" id="btn" value="Toevoegen/Updaten" />
<ol id="lijst">
</ol>
</body>
</html>
There is no list output how do i correct this?..
I really can't find the solution, what did i miss.. huh?
You had a few things missing,
The HTML code.
The winkel object was undefined.
The VulLijst function was doing nothing... because addProduct was taking care of this already.
You are relying on the instance fields (this.naam and this.prijs), but what you want to do is pass in method parameters (external variables).
As for updating, you will need to store a list of Products, clear the child elements of lijst, and re-add the items that represent the list.
Note: One thing I am confused about is why you named your class—that represents a list—Product, when it should really be an Inventory that allows you to ADD Product objects.
Code
// Uncaught ReferenceError: winkel is not defined
var winkel = new Product();
function Product(naam, prijs) {
this.naam = naam;
this.prijs = prijs;
}
Product.prototype.addProduct = function(naam, prijs) {
naam = naam || this.naam; // Default or instance field
prijs = prijs || this.prijs; // Default or instance field
console.log(naam, prijs);
var elol = document.getElementById("lijst");
var nieuwNaam = document.createElement("li");
nieuwNaam.textContent = naam;
elol.appendChild(nieuwNaam);
var nieuwPrijs = document.createElement("li");
nieuwPrijs.textContent = prijs;
elol.appendChild(nieuwPrijs);
}
Product.prototype.getProducten = function(naam, prijs) {
naam = naam || this.naam; // Default or instance field
prijs = prijs || this.prijs; // Default or instance field
return naam + " (€ " + prijs + ")";
}
document.addEventListener("DOMContentLoaded", function() {
winkel.addProduct("Potlood", 10); // Why are you adding a product to a product?
var elBtn = document.getElementById("btn");
elBtn.onclick = VoegProductToe;
});
function VoegProductToe() {
var naam = document.getElementById("txtNaam").value;
var prijs = document.getElementById("txtPrijs").value;
winkel.addProduct(naam, prijs);
}
label { font-weight: bold; }
<label>Product</label>
<input id="txtNaam" value="Something" />
<input id="txtPrijs"value="1.99" />
<button id="btn">Add</button>
<br/>
<ul id="lijst"></ul>
Explained
I will openly admit, I'm not 100% sure what you're trying to do, I assume that's due to a language barrier my side though, I'm not sure of the natural language that you use on a daily basis, i.e. some of the variable names seem unclear to me, but that's my problem, not yours! :)
Anyway, I used some guess work to figure out what you're trying to achieve, and I assumed that you're simply trying to have some sort of product list where each product has a name and a price attached to it?
You want to be able to add a product to the list, based on two input fields, then some button to add to/update that product list.
I've broken up the code into a couple of simple functions, with this solution you can add/remove as many functions, classes or whatever you want. In this answer you can clearly see that there's some render function, and some onUpdate function, I just went with these generic names for the sake of simplicity.
If you have any issues with this solution, please provide as much feedback as possible! I hope that it's been of some help one way or another.
// A simple product list.
const ProductList = () => {
const products = [];
let el = null;
// What you wish to return, aka an object...
return {
addProduct: (name, price) => {
products.push({
name: name,
price: price
});
onUpdate();
render(el, products);
},
setRoot: root => {
el = root;
},
// removeFromList, etc...
};
};
// A simple on update function.
const onUpdate = () => {
console.clear();
console.log('Update!');
};
// A 'simple' render function.
const render = (el, products) => {
if (el == null) return;
const template = obj => `<li>${obj.name} €${obj.price}</li>`;
let html = '';
products.forEach(product => html += template(product));
el.innerHTML = html;
};
// A function to dispatch some event(s).
const dispatchEvents = products => {
const btn = document.getElementById("btn");
const price = document.getElementById("price");
const name = document.getElementById("name");
// Just an example.
const isValid = () => {
if (price.value != '' && name.value != '') return true;
return false;
};
// Handle the on click event.
btn.onclick = () => {
if (isValid()) {
products.addProduct(name.value, price.value);
name.value = '';
price.value = '';
}
};
};
// A simple dom ready function.
const ready = () => {
const products = ProductList();
products.setRoot(document.getElementById("productList"));
products.addProduct('Demo', 10);
products.addProduct('Other', 19.99);
dispatchEvents(products);
};
document.addEventListener("DOMContentLoaded", ready);
<div>
<label for="name">name:</label>
<input type="text" id="name" />
</div>
<div>
<label for="price">Prijs:</label>
<input type="number" id="price" />
</div>
<input type="button" id="btn" value="Update" />
<ol id="productList">
</ol>

Get the value of a specific child from the result of a query in a Firebase database in Javascript

I have this sample database on Firebase:
Sample database
I have an index.html that have these two input text:
...
<!-- LOGIN -->
<div class="login-form" id="login">
<h2>Login Form</h2>
<input type="text" name="username" id="username" placeholder="Username">
<input type="password" name="password" id="password" placeholder="Password">
<a class="btn-login" id="btn-login">Login</a>
...
I want to select a child that have the same "Username" of the inputText and then I want to verify if the password match.
I've tried with these query in the index.js file:
var firebaseRootRef = firebase.database().ref();
var personale_Ref = firebaseRootRef.child('DatabaseTirocinio/Personale');
$(function() {
$('#btn-login').click(function() {
var id_user = $("#username").val();
var id_password = $("#password").val();
personale_Ref.orderByChild("Username").equalTo(id_user).on("value", function(snapshot) {
console.log(snapshot.val());
var dip = personale_Ref.child(snapshot.key);
dip.equalTo("Password").on("value", function(child) {
console.log(child.val());
});
});
});
});
The first "console.log(snapshot.val())" show the right select of the child with the "Username" that I search for:
First consoleLog
But the second "console.log(child.val())" return "null".
Can anyone help me?
Ok, I've find a solution (thanks to Himanshu), maybe not the best solution, so if anyone has any suggestion to improve it please leave a reply:
var firebaseRootRef = firebase.database().ref();
var personale_Ref = firebaseRootRef.child('DatabaseTirocinio/Personale');
$(function() {
$('#btn-login').click(function() {
var id_user = $("#username").val();
var id_password = $("#password").val();
personale_Ref.orderByChild("Username").equalTo(id_user).on("value", function(snapshot) {
var dipendente = snapshot.val();
var dipKey = Object.keys(dipendente);
var k = dipKey[0];
if (dipendente[k].Password == id_password) {
console.log("Ok");
} else
console.log("Wrong password");
});
});
});
Check if the snap you are returning in the second query exists. It will tell you if the user with the password that has been entered exists in the database if not it will return null.
var firebaseRootRef = firebase.database().ref();
var personale_Ref = firebaseRootRef.child('DatabaseTirocinio/Personale');
$(function() {
$('#btn-login').click(function() {
var id_user = $("#username").val();
var id_password = $("#password").val();
personale_Ref.orderByChild("Username").equalTo(id_user).on("value", function(snapshot) {
console.log(snapshot.val());
var dip = personale_Ref.child(snapshot.key);
if(snapshot.exists()){
Object.keys(snapshot.val()).map(k => {
if(k == "Password"){
console.log(snapshot.val()[k])
}
})
}
});
});
});

Firebase Data Not Saving to Database

I'm having a problem attempting to add data to Firebase. Disregard the vars I don't use as I am trying different things and have commented out stuff I am not using at the moment.
But essentially, what I want to do is save this data to Firebase as follows:
A user enters his name and age in input boxes and then hits submit.
Once he/she hits submit, the function addFB() runs and ideally would create a child called users, and then under that, create a new child with the newly typed in userName (the User's name from the input box), and store his name and age in that child.
However, nothing is going to Firebase from this. Please help. Thanks in advance!
<h2>Add</h2>
<input type=text" id="userName">
<input type="number" id="userAge">
<button id="btUpdateMessage" margin-bottom="20px" onclick="addFB()"> Update</button>
<script>
var lblCurrentMessage = document.getElementById('lblCurrentMessage'),
userName = document.getElementById('userName'),
btUpdateMessage = document.getElementById('btUpdateMessage'),
userAge = document.getElementById('userAge'),
rootRef = new Firebase('https://********.firebaseio.com');
var usersRef = rootRef.child('users');
function addFB() {
usersRef.child(userName).set({
Name: userName,
Age: userAge
});
userName.value = '';
userAge.value = '';
}
*rootRef = new Firebase('https://********.firebaseio.com');*
The above code is not correct. This is the old method.
Just check the below code. This will help you.
function addFB() {
var userName = document.getElementById('userName'),
userAge = document.getElementById('userAge');
firebase.database().ref('users/' + userName).set({
Name: userName,
Age: userAge
});
}
What about this?
var rootRef = Firebase('https://********.firebaseio.com');
var contactsRef = rootRef .child('users');
function addFB() {
contactsRef.child(userName)
.push({
userName: document.getElementById('userName').value,
userAge: document.getElementById('userAge').value
});
Name.value = '';
Age.value = '';
}

Printing or Echoing message in html page from javascript

I have the following script
function validateEmailp() {
var messagemail = document.getElementById('emailerrorz').innerText;
var two = document.getElementById('email').value;
var first = two.split("#")[1];
var badEmails = ["gmail.com", "yahoo.com"]
if (badEmails.indexOf(first) != -1) {
document.getElementById("email").value = ""; //this works
messagemail = 'We do not accept free e-mails'; //this doesn't
return false;
}
return true;
}
and HTML
<td>{EMAILFIELD}<span id="emailerrorz"></span></td>
and {EMAILFIELD} is in PHP
<input id="email" class="txt" type="text" name="email" size="25" value="" maxlength="255" onblur="validateEmailp()"></input>
But it doesn't work for me on printing the error in the span id. It only works on resetting the value from there.
When you do var messagemail = document.getElementById('emailerrorz').innerText; your variable stores a string with that content.
When you var messagemail = document.getElementById('emailerrorz'); your variable stores a object/element and then you can use the property .innerText
So use:
var messagemail = document.getElementById('emailerrorz');
// rest of code
messagemail.innerText = 'We do not accept free e-mails';
Properties don't work this way. You want:
document.getElementById('emailerrorz').innerText = 'We do not accept free e-mails'
or
var messagemail = document.getElementById('emailerrorz');
....
messagemail.innerText = etc
http://jsfiddle.net/MJXEg/

Categories