So, I have an array stored in local storage called "users", with the fields "email", "id", "img", "pass", "user" and "usertype".
I want to have a field in which the user can change his email, but I can't do it. I tried this but it didn't work:
let loggedID = JSON.parse(localStorage.getItem("loggedID"))
changeEmailLink.addEventListener('click', function () {
users = JSON.parse(localStorage.getItem("users"))
users[loggedID].email = document.getElementById('changeEmail').value
})
I think the only thing I'm missing is using "localstorage.setItem()" to apply the change, but I'm afraid I'll delete the user records I have stored already if I don't do it right.
Any help would be apreciated. Thanks!
P.S. I am sure the "loggedID" is working since I already used it multiple times on this project. Also no jquery please, only vanilla JS. :)
I figured it out!
changeEmailLink.addEventListener('click', function () {
users = JSON.parse(localStorage.getItem("users"))
let usersUpd = users
for (i = 0; i < users.length; i++) {
if (users[i].email == users[loggedID].email) {
usersUpd[i].email = document.getElementById('changeEmail').value
} else {
usersUpd[i] = users[i]
}
localStorage.setItem("users", JSON.stringify(usersUpd))
}
})
This is what I did and it works great.
All you need to do is use the setItem function to maintain the new state.
localStorage
function setEmail(email) {
let loggedID = JSON.parse(localStorage.getItem("loggedID"))
let users = JSON.parse(localStorage.getItem("users"))
let user = users[loggedID]
user.email = email;
localStorage.setItem("users", users)
}
changeEmailLink.addEventListener('click', function () {
setEmail(document.getElementById('changeEmail').value)
})
Related
I have a problem with the getItem of my localStorage in my React Form. I put a onChange attribute:
<div className = 'InputForm' onChange={save_data}>
I found the setItem function to store the data in. Here is the function:
function save_data(){
let textarea = document.querySelectorAll("textarea")
let input = document.querySelectorAll("input[type='text']")
let saved_fields = []
textarea.forEach(x => {
saved_fields.push({
key: x.className,
value: x.value
})
})
input.forEach(x => {
saved_fields.push({
key: x.className,
value: x.value
})
})
localStorage.setItem("saved_data", JSON.stringify(saved_fields))
}
My main problem is that I don't find a way to put the data back to the page after the page reload. I just found out how to persist all my inputs in the console:
window.onload = dataLoad();
function dataLoad () {
let show_saved_data = localStorage.getItem("saved_data");
console.log('show_saved_data:',JSON.parse(show_saved_data));
}
Can you guys help me find the retrieve/persist data function?
Edit : Here is the html of the form, i use props from another component. I don't know if this can change the function i need to use.
<InputFields
stateKey = 'contactInfo'
key = {props.contactInfo.id}
completedFields = {props.contactInfo}
templateFields = {props.templates.contactInfo}
onDataEntry = {props.onDataEntry}
newField = {props.newField}
/>
Can we have your HTML form to help you? You should not identify your inputs / textareas by their className.
After that, by using ID as identifiers for your input / textarea, you just have to do it in reverse:
Get your input/textarea list
forEach items, set the value based on the ID
function dataLoad () {
var show_saved_data = localStorage.getItem("saved_data");
var inputList = JSON.parse(show_saved_data);
inputList.forEach(x => {
document.getElementById(x.key).setAttribute('value', x.value);
})
}
Giving us your complete HTML/JS will be easier to give you a complete solution.
I have a struggle with updating Local Storage values. I have "users" array from which I want to update my Local Storage, buy many problems have occured durning implementation. Please see code below, and also take note its only learning so dont be scared I use local storage for stroing login and password.
class Register {
constructor({
inputLogin,
inputPassword
}) {
this.inputLogin = inputLogin;
this.inputPassword = inputPassword;
}
users = [];
add() {
const btn = document.querySelector('#register-form__submit');
btn.addEventListener('click', (e) => {
e.preventDefault();
const usersData = {
login: this.inputLogin.value,
password: this.inputPassword.value
}
if (localStorage.getItem('users')) {
// // I dont know what to do here, I want to get existing value from local Storage. Put them back to array users and then set local storage with this old an new value... But I've encountered a lot of problems like nested arrays, overlooping etc. Please tell me guys how you would've done it.
} else {
this.users.push(usersData);
localStorage.setItem('users', JSON.stringify(this.users));
}
})
}
}
EDIT: Working solution. I hope it helps sombeody who wants to practice and doesn't know databases yet.
class Register {
constructor() {
this.inputLogin = document.getElementById('login')
this.inputPassword = document.getElementById('password')
this.users = []
}
add() {
//checking if inputs are empty
if (this.inputLogin.value === '' || this.inputPassword.value === '') {
this.alert('Musisz wypełnić wszystkie pola')
} else {
//creating object with users data
let userData = {
login: this.inputLogin.value,
password: this.inputPassword.value,
}
if (window.localStorage.getItem('users')) {
//checking if there are any users in local storage
const existingData = JSON.parse(window.localStorage.getItem('users'));
//looping through those values and checking if there is already such an user with this login.
for (let i = 0; i < existingData.length; i++) {
if (existingData[i].login === userData.login) {
if (document.querySelector('.red-alert')) {
return;
} else {
this.alert("user already exists");
break;
}
} else {
//checking if this.users[] is empty(this happens after refreshing page or restarting browser of course
if (this.users.length === 0) {
existingData.map((obj) => {
return this.users.push(obj);
})
this.users.push(userData);
localStorage.setItem('users', JSON.stringify(this.users))
window.location.href = "index.html";
}
//checking if there is some data in this.users. That means page was not refreshed nor browser was restarted.
else if (this.users.length > 0) {
this.users.push(userData);
localStorage.setItem('users', JSON.stringify(this.users))
console.log(this.users);
window.location.href = "index.html";
}
}
}
}
else {
//success when there are no users at all in this.users[] and local storage is empty
this.users.push(userData);
localStorage.setItem('users', JSON.stringify(this.users))
window.location.href = "index.html";
}
}
alert(text) {
const par = document.createElement('p')
par.classList.add('red-alert');
par.textContent = text;
document.querySelector('.register-form').appendChild(par)
}
}
You need to first check for the existing key and then update the value of the local storage. Have added in line comments for better understanding
// ..rest of the code
// check if the local storage have any key by this na,e
const currStoredData = localStorage.getItem('users');
// if key esxist
if (currStoredData) {
// push the existing value of the key in the array
this.users.push(currStoredData);
// set the new user data in the local storage
localStorage.setItem(usersData)
} else {
this.users.push(usersData);
localStorage.setItem('users', JSON.stringify(this.users));
}
})
You could read the local storage only at the beginning and work with the object after.
Because the storage only saves strings, you need to parse the value as well.
class Register {
constructor({
inputLogin,
inputPassword
}) {
this.inputLogin = inputLogin;
this.inputPassword = inputPassword;
}
users = JSON.parse(localStorage.getItem('users')) || [];
add() {
const btn = document.querySelector('#register-form__submit');
btn.addEventListener('click', (e) => {
e.preventDefault();
const usersData = {
login: this.inputLogin.value,
password: this.inputPassword.value
}
this.users.push(usersData);
localStorage.setItem('users', JSON.stringify(this.users));
})
}
}
I am wanting some help with this project I am working on. The part needed for this question is that the user creates a button and then can click on it to update parts of the page based on the id (created from the user input) of that button. This works.
However, I want to be able to save and retrieve these buttons using localStorage. I have worked with localStorage before, but nothing I try seems to work. Is it even possible to store HTML elements locally?
Just looking for some clarification of how I should go about this, or an example.
Thanks, Elliot.
on page load:
if (typeof(Storage) !== "undefined") {
let groupsLoaded = localStorage.getItem("storedGroupArray");
$("#createdGroups").prepend(groupsLoaded);
}
when creating and (hopefully) storing buttons:
let groupArray = [];
function addGroup() {
let userInput = $("#groupName").val();
if(userInput.length >= 1) {
let newGroup = $(`<button id='${userInput}' class='createdGroupsButton'>${userInput}</button>`);
$("#createdGroups").append(newGroup);
groupArray.unshift(newGroup);
let groups = localStorage.setItem("storedGroupArray", userInput);
$("#groupName").val("");
} else {
alert("Please enter a group name.")
}
};
LINK TO CODE SO FAR:
https://codepen.io/elliot7-7/pen/zYvrBWy
(Ignore the task sections)
I would store an array of created group names in localStorage.
Later on they can be retrieved and processed as html elements with specified template.
let groupArray = [];
let groupNames = [];
function addGroup() {
let userInput = $("#groupName").val();
if(userInput.length >= 1) {
let newGroup = $(`<button id='${userInput}' class='createdGroupsButton'>${userInput}</button>`);
$("#createdGroups").append(newGroup);
groupArray.unshift(newGroup);
groupNames = [...groupNames, userInput];
localStorage.setItem("storedGroupArray", JSON.stringify(groupNames));
$("#groupName").val("");
} else {
alert("Please enter a group name.")
}
};
if (typeof(Storage) !== "undefined") {
let storedGroupNames = JSON.parse(localStorage.getItem("storedGroupArray"));
if(storedGroupNames) {
for(let groupName of storedGroupNames) {
let newGroup = $(`<button id='${groupName}' class='createdGroupsButton'>${groupName}</button>`);
$("#createdGroups").append(newGroup);
}
}
}
I'm trying to solve this problem since couple of hours but I'm not succeeding. I'm a beginner at programming so please excuse me if i made a dumb mistake. Thanks a lot.
The following code doesn't work when username and password are declared globally.
const form = document.querySelector ('.form');
const feedback = document.querySelector ('.feedback');
const patternPassword = /^[a-zA-Z0-9]{6,}$/;
const patternUsername = /^[a-zA-Z]{5,15}$/;
const username = form.username.value;
const password = form.pass.value;
form.addEventListener ('submit', (e) =>{
e.preventDefault();
if (patternUsername.test (username) && (patternPassword.test (password))) {
feedback.textContent = 'Congrats! You Have signed up.';
} else {
feedback.textContent = 'Wrong details.';
}
});
But when i declare username and password locally like below. They do work. But I need to declare them globally because i need to use them somewhere else.
const form = document.querySelector ('.form');
const feedback = document.querySelector ('.feedback');
const patternPassword = /^[a-zA-Z0-9]{6,}$/;
const patternUsername = /^[a-zA-Z]{5,15}$/;
form.addEventListener ('submit', (e) =>{
const username = form.username.value;
const password = form.pass.value;
e.preventDefault();
if (patternUsername.test (username) && (patternPassword.test (password))) {
feedback.textContent = 'Congrats! You Have signed up.';
} else {
feedback.textContent = 'Wrong details.';
}
});
Also, if i don't use the variables and just reference the inputs like 'form.username.input' in the regex test method, it works that way too.
const form = document.querySelector ('.form');
const feedback = document.querySelector ('.feedback');
const patternPassword = /^[a-zA-Z0-9]{6,}$/;
const patternUsername = /^[a-zA-Z]{5,15}$/;
form.addEventListener ('submit', (e) =>{
e.preventDefault();
if (patternUsername.test (form.username.value) && (patternPassword.test (form.pass.value))) {
feedback.textContent = 'Congrats! You Have signed up.';
} else {
feedback.textContent = 'Wrong details.';
}
});
Any help would be really appreciated because this problem is making me crazy.
So, I wanna mark this problem as solved and I read somewhere to post an answer yourself and mark it solved.
Below is the solution to the problem as #teemu mentioned.
The values to the global variables are read when the page loads, at that time the inputs are empty. That's why you need to read the values in the event listener. You can declare a function, which reads the values, then call that function whenever you need password and username.
Edit: RIP, it says you'll be able to accept the answer in 2 days.
Hoping someone out there could tell me where I am going wrong with this update method:
changeTaskDetails: function(singleID,detailsTarget){
TaskDetails.update({
_id: singleID,
}, {
$set:{
projectType: detailsTarget,
}
});
console.log(singleID);
},
Here is the event:
'submit #editTaskDetails'(event){
event.preventDefault();
var id = FlowRouter.getParam('taskId');
const singleDetailsUpdate = Tasks.findOne({_id:id});
const singleID = singleDetailsUpdate._id;
const target = event.target;
const facilityTarget = target.facilityName.value;
const inspectorTargetName = target.detailsinspector.value;
const inspectorIdTarget = target.inspectorid.value;
const detailsTarget = target.detailstype.value;
const dateTarget = target.TaskDate.value;
console.log(singleID)
Meteor.call("changeTaskDetails", singleID,detailsTarget);
},
I can get the 2 props to log...but its not updating the DB. No errors in either console.
I figured it out! I had a session variable controlling when you could (or could not) see the update form. For one reason or another the form crapped out when inside of this area. When I removed the session, and added the form to the main template...it worked!