As the title says, I want to use localstorage to store 2 things: accounts, and products and information of it. First, I got the accounts part working using this code:
function signup(e) {
event.preventDefault();
var email = document.getElementById("email").value;
var username = document.getElementById("username").value;
var pass = document.getElementById("password").value;
var user = {
number: 1,
email: email,
username: username,
password: pass
};
var json = JSON.stringify(user);
localStorage.setItem(username, json);
}
function login(e) {
event.preventDefault();
var username = document.getElementById("username").value;
var pass = document.getElementById("password").value;
var result = document.getElementById("result");
var user = localStorage.getItem(username);
var data = JSON.parse(user);
if (user == null) {
result.innerHTML = "Wrong Username";
} else if (username == data.username && pass == data.password) {
result.innerHTML = "Logged In";
for (var i = 0; i < localStorage.length; i++) {
var keys = Object.keys(localStorage);
var datas = JSON.parse(localStorage.getItem(keys[i]));
var datauser = datas.username;
datas.number = 2;
var jsonval = JSON.stringify(datas);
localStorage.removeItem(keys[i]);
localStorage.setItem(datauser, jsonval)
}
localStorage.removeItem(username);
data.number = 1;
var json = JSON.stringify(data);
localStorage.setItem(username, json);
} else {
result.innerHTML = "Wrong Password";
}
}
function getaccount() {
for (var i = 0; i < localStorage.length; i++) {
var keys = Object.keys(localStorage);
var data = JSON.parse(localStorage.getItem(keys[i]));
if (data.number == 1) {
document.getElementById("accountnamep").innerHTML = data.username;
document.getElementById("name").innerHTML = data.username;
}
}
}
and then I have a code for my products but I dont know how I would show it in a "your cart" file but the code I have currently is:
var tocart = {
name: name,
price: price,
size: size,
quantity: quantity,
shipping: shipping
};
var json = JSON.stringify(tocart);
localStorage.setItem(name, json);
Related
I tried to send my variable back from foreground.js to background.js by using an unchanged variable, and it works. Now I can't send some data that I use my AddEventListener syntax to store the data into the variable to call its back to background.js here are my code on foreground.js
foreground.js
console.log("foreground.js injected");
var pswdBtns = [];
let hrefLists = [];
var data = {};
var i;
function readUUID(){
var navigator_info = window.navigator;
var screen_info = window.screen;
var uid = navigator_info.mimeTypes.length;
uid += navigator_info.userAgent.replace(/\D+/g, '');
uid += navigator_info.plugins.length;
uid += screen_info.height || '';
uid += screen_info.width || '';
uid += screen_info.pixelDepth || '';
return uid;
}
async function passwordProtected(pointerList){
const date = new Date();
const uid = readUUID();
alert("You are in dangerous on \'"+ pointerList.title + "\' row = " + pointerList.id.slice(20));
data = {
"Webtitle": pointerList.href,
"Title": pointerList.title,
"Time": date.toString(),
"UUID": uid
}
console.log("foreground = ", data);
return data;
}
console.log("Start loop")
//This function made for collect each id in passwordShowPasswordButton
for(i = 0; i<=pswdBtns.length; i++){
if(document.querySelector("#passwordShowPasswordButton_"+ i) == null){
console.log("This is your limit!!");
}
else{
hrefLists[i] = document.querySelector("#passwordWebsitelink_"+ i);
pswdBtns[i] = document.querySelector("#passwordShowPasswordButton_"+ i);;
data = pswdBtns[i].addEventListener('click', passwordProtected.bind(pswdBtns[i], hrefLists[i]));
console.log(hrefLists[i].title); /* Title VARCHAR(30) */
console.log(hrefLists[i].href); /* Website VARCHAR(50) */
}
}
console.log("End");
and these are my code on background.js
background.js
const edgePswd = "edge://settings/passwords";
const settingPage = "edge://settings/";
chrome.tabs.onActivated.addListener(async (tab) => {
await chrome.tabs.get(tab.tabId, (current_tab_info) => {
var pswdPageChecked = 1;
while(pswdPageChecked < 2) {
if (edgePswd == current_tab_info.url) {
chrome.tabs.executeScript(null, { file: "/extension/foreground.js" }, (data) => {
console.log("Coming to foreground");
console.log(data);
});
pswdPageChecked++;
}
}
});
});
It would be a pleasure if someone can figure this.
I'm having an issue with creating the array in the first place I couldn't push (person) to the array. I changed my code several times because of this error and I tried to define the array inside and outside the function but nothing changed.
the error
testreg.php:53 Uncaught TypeError: Cannot read properties of null (reading 'push')
Thanks for the help.
var feedback = document.getElementById("feedback");
var userArray = JSON.parse(localStorage.getItem("key"));
var person = {
name: document.getElementById("nameinput").value,
email: document.getElementById("emailinput").value,
passowrd: document.getElementById("passwordinput").value };
function checkemail(userArray, email) {
var i;
var userArray = JSON.parse(localStorage.getItem("key"));
let isFound = false;
if(userArray != undefined)
for (i = 0; i < userArray.length; i++) {
let oldemail = userArray[i].email;
let newemail = document.getElementById("emailinput").value;
if (newemail === oldemail) { isFound = true; i = userArray.length;
return feedback.innerHTML = "email exist please log in or register with different email";
}}
if(!isFound) {
return storeName(person, userArray);
}}
function storeName(person, userArray){
var person = {
name: document.getElementById("nameinput").value,
email: document.getElementById("emailinput").value,
passowrd: document.getElementById("passwordinput").value };
var userArray = JSON.parse(localStorage.getItem("key"));
userArray.push(person);
userArray = JSON.stringify(userArray)
localStorage.setItem("key", userArray);
console.log(userArray);
}
function clearStorage(){
localStorage.clear();
}
I am making this announcement program for teachers and students where the teacher puts in values such as grade gender club and the announcement, and a student page that lets you choose the grade gender and club you are in to show the announcements that are there for those values. Now I have a problem. I have created an array which allows for me to put in multiple different announcements but I cant get the array to function and show up in the student page. Here are the 2 different js codes
Teacher page js code
var teacherGrade = [];
var teacherGender = [];
var teacherClub = [];
var teacherAnnouncement = [];
var counter = 0;
function getData() {
//alert("here");
teacherGrade[counter] = document.getElementById("htmlTGrade").value
teacherGender[counter] = document.getElementById("htmlTGender").value
teacherClub[counter] = document.getElementById("htmlTClub").value
teacherAnnouncement[counter] = document.getElementById("htmlTAnnouncement").value
localStorage.setItem("teacherGradeKey", JSON.stringify(teacherGrade));
localStorage.setItem("teacherGenderKey", JSON.stringify(teacherGender));
localStorage.setItem("teacherClubKey", JSON.stringify(teacherClub));
localStorage.setItem("teacherAnnouncementKey", JSON.stringify(teacherAnnouncement));
counter++;
}
function getExsistingAnnouncement() {
if (JSON.parse(localStorage.getItem("teacherGradeKey")) != null) {
teacheGrade = JSON.parse(localStorage.getItem("teacherGradeKey"));
teacherGender = JSON.parse(localStorage.getItem("teacherGenderKey"));
teacherClub = JSON.parse(localStorage.getItem("teacherClubKey"));
teacherAnnouncement = JSON.parse(localStorage.getItem("teacherAnnouncementKey"));
counter = teacherGrade.length;
}
}
//function checkArray() {
//var checkGrade = JSON.parse(localStorage.getItem("teacherGrade"));
//alert("Grade from Local Storage = ", checkGrade);
//var checkGender = JSON.parse(localStorage.getItem("teacherGender"));
//alert("Gender from Local Storage = ", checkGender);
//var checkClub = JSON.parse(localStorage.getItem("teacherClub"));
//alert("Club from Local Storage = ", checkClub);
//var checkAnnouncement = JSON.parse(localStorage.getItem("teacherAnnouncement"));
//alert("Announcement from Local Storage = ", checkAnnouncement);
//}
Student Page js code
var teacherGrade = [];
var teacherGender = [];
var teacherClub = [];
var teacherAnnouncement = [];
var studentGrade;
var studentGender;
var studentClub;
var counter = 0;
var annoucnementTextHolder = " ";
function displayAnnouncement() {
teacherGrade[counter] = localStorage.getItem("teacherGradeKey");
teacherGender[counter] = localStorage.getItem("teacherGenderKey");
teacherClub[counter] = localStorage.getItem("teacherClubKey");
teacherAnnouncement[counter] = localStorage.getItem("teacherAnnouncementKey");
studentGrade = localStorage.getItem("studentGradeKey");
studentGender = localStorage.getItem("studentGenderKey");
studentClub = localStorage.getItem("studentClubKey");
annoucnementTextHolder += teacherAnnouncement;
counter++;
for (var i = 0; i < teacherGrade.length; i++) {
if ((teacherGrade[i] == studentGrade || teacherGrade[i] == "Select all") && (teacherGender[i] == studentGender || teacherGender[i] == "Select all") && (teacherClub[i] == studentClub || teacherClub[i] == "Select all")) {} else {
document.getElementById("htmlSViewerText").innerHTML = "Sorry no announcement"
}
}
document.getElementById("htmlSViewerText").innerHTML = annoucnementTextHolder;
}
I have a function for the user to be able to change his own details in his account like his description or social links etc...
However, when I submit the form, it replaces everything and the empty values just erase the field in the database.
Any way to submit the form and replace ONLY the values that have been entered in the field and ignore the empty ones ?
Here is my controller :
var database = firebase.database();
var userId = firebase.auth().currentUser.uid;
var nameInput = document.querySelector('#name');
var descriptionInput = document.querySelector('#description');
var cityInput = document.querySelector('#city');
var ageInput = document.querySelector('#age');
var hobbiesInput = document.querySelector('#hobbies');
var facebookInput = document.querySelector('#facebook');
var twitterInput = document.querySelector('#twitter');
var instagramInput = document.querySelector('#instagram');
var youtubeInput = document.querySelector('#youtube');
var snapchatInput = document.querySelector('#snapchat');
var linkedinInput = document.querySelector('#linkedin');
var emailInput = document.querySelector('#email');
var passwordInput = document.querySelector('#password');
var saveButton = document.querySelector('#save');
saveButton.addEventListener("click", function() {
var name = nameInput.value;
var description = descriptionInput.value;
var city = cityInput.value;
var age = ageInput.value;
var hobbies = hobbiesInput.value;
var facebook = facebookInput.value;
var twitter = twitterInput.value;
var instagram = instagramInput.value;
var youtube = youtubeInput.value;
var snapchat = snapchatInput.value;
var linkedin = linkedinInput.value;
var email = emailInput.value;
var password = passwordInput.value;
firebase.database().ref('accounts/' + userId).set({
name: name,
description: description,
city: city,
age: age,
hobbies: hobbies,
facebook: facebook,
twitter: twitter,
instagram: instagram,
youtube: youtube,
snapchat: snapchat,
linkedin: linkedin,
email: email,
password: password,
});
receiveNewData();
function receiveNewData() {
// check if there's new data added
firebase.database().ref('accounts/' + userId).on('child_added', function(msg) {
var data = msg.val();
// your new data
console.log(data);
$state.go("tab.account");
});
}
});
var firebase_data = {};
var userID = firebase.auth().currentUser.uid;
var input_data = {
nameInput: document.querySelector('#name'),
descriptionInput: document.querySelector('#description'),
cityInput: document.querySelector('#city'),
ageInput: document.querySelector('#age'),
hobbiesInput: document.querySelector('#hobbies'),
facebookInput: document.querySelector('#facebook'),
twitterInput: document.querySelector('#twitter'),
instagramInput: document.querySelector('#instagram'),
youtubeInput: document.querySelector('#youtube'),
snapchatInput: document.querySelector('#snapchat'),
linkedinInput: document.querySelector('#linkedin'),
emailInput: document.querySelector('#email'),
passwordInput: document.querySelector('#password'),
saveButton: document.querySelector('#save')
}
for(var key in input_data) {
if(input_data.hasOwnProperty(key) && input_data[key].value.length) {
firebase_data[key] = input_data[key].value
}
}
firebase.database().ref('accounts/' + userId).set(firebase_data)
For the people, like me, that are new to this, here is the solution I found : Autocomplete the fields that have a value already so when I submit the form it is saved again with the same value.
The code :
var database = firebase.database();
var userId = firebase.auth().currentUser.uid;
var nameInput = document.querySelector('#name');
var descriptionInput = document.querySelector('#description');
var cityInput = document.querySelector('#city');
var ageInput = document.querySelector('#age');
var hobbiesInput = document.querySelector('#hobbies');
var facebookInput = document.querySelector('#facebook');
var twitterInput = document.querySelector('#twitter');
var instagramInput = document.querySelector('#instagram');
var youtubeInput = document.querySelector('#youtube');
var snapchatInput = document.querySelector('#snapchat');
var linkedinInput = document.querySelector('#linkedin');
var emailInput = document.querySelector('#email');
var passwordInput = document.querySelector('#password');
var saveButton = document.querySelector('#save');
var database = firebase.database().ref('/accounts/' + userId);
// Retrieve information into the fields already filled in Database
database.on('value', function(snapshot) {
var displayName = snapshot.val().name;
var description = snapshot.val().description;
var displayCity = snapshot.val().city;
var displayAge = snapshot.val().age;
var displayHobbies = snapshot.val().hobbies;
var displayFacebook = snapshot.val().facebook;
var displayTwitter = snapshot.val().twitter;
var displayInstagram = snapshot.val().instagram;
var displayYoutube = snapshot.val().youtube;
var displaySnapchat = snapshot.val().snapchat;
var displayLinkedin = snapshot.val().linkedin;
var displayEmail = snapshot.val().email;
var displayPassword = snapshot.val().password;
$scope.$apply(function() {
$scope.displayName = displayName;
$scope.description = description;
$scope.displayCity = displayCity;
$scope.displayAge = displayAge;
$scope.displayHobbies = displayHobbies;
$scope.displayFacebook = displayFacebook;
$scope.displayTwitter = displayTwitter;
$scope.displayInstagram = displayInstagram;
$scope.displayYoutube = displayYoutube;
$scope.displaySnapchat = displaySnapchat;
$scope.displayLinkedin = displayLinkedin;
$scope.displayEmail = displayEmail;
$scope.displayPassword = displayPassword;
});
document.getElementById("name").value = displayName;
document.getElementById("description").value = description;
document.getElementById("city").value = displayCity;
document.getElementById("age").value = displayAge;
document.getElementById("hobbies").value = displayHobbies;
document.getElementById("facebook").value = displayFacebook;
document.getElementById("twitter").value = displayTwitter;
document.getElementById("instagram").value = displayInstagram;
document.getElementById("youtube").value = displayYoutube;
document.getElementById("snapchat").value = displaySnapchat;
document.getElementById("linkedin").value = displayLinkedin;
document.getElementById("email").value = displayEmail;
document.getElementById("password").value = displayPassword;
});;
I have a form that takes information and outputs it in a div if its complete. If the form is not complete, output is error messages relating to the specific field which needs correcting. The error messages/output update as information is changed and the button is clicked.
Currently valid output will update as it changes, but going between valid output and error messages, the two sets of text both appear on the page, and then remain there until I refresh the page. Here's the code:
/*
Project 1 - AJAX 2015
2/14/15
Mitch Gundrum
*/
/*
Function to create input and HTML elements,
Create output nodes; output div
*/
function init() {
//Output Div
var div = document.createElement("div");
div.id = "output";
//Name
var name = document.getElementById("name").value;
name.type = "text";
//Address
var address = document.getElementById("address").value;
address.type = "text";
var city = document.getElementById("city").value;
city.type = "text";
var state = document.getElementById("state");
state.type = "text";
var index = state.selectedIndex;
var fullState = state.options[index];
var zip = document.getElementById("zip").value;
zip.type = "text";
//Email
var email = document.getElementById("email").value;
email.type = "text";
//Phone Number
var areaCode = document.getElementById("areaCode").value;
areaCode.type = "text";
var prefix = document.getElementById("prefix").value;
prefix.type = "text";
var suffix = document.getElementById("suffix").value;
suffix.type = "text";
//Gender
var gender = document.getElementsByName("gender");
var genderChoice = "";
for (var i = 0; i < gender.length; i++) {
if (gender[i].checked) {
genderChoice += gender[i].value;
}
}
//Previous Courses
var courses = document.getElementsByName("courses");
var courseChoice = "";
for (var e = 0; e < courses.length; e++) {
if (courses[e].checked) {
courseChoice += courses[e].value + ", ";
}
}
//Call Validate form method; pass all elements
validateForm(div, name, address, city, fullState, zip,
email, areaCode, prefix, suffix, genderChoice,
courseChoice);
}
//Check all elements for null
function validateForm(div, name, address, city, fullState, zip,
email, areaCode, prefix, suffix, genderChoice,
courseChoice) {
var RUN_OUTPUT = 1;
function br() {
return document.createElement('br');
}
if (name == null || name == "") {
var nameError = "Name is not valid";
var printNameError = document.createTextNode(nameError);
var nameLabel = document.getElementById("nameError");
nameLabel.appendChild(printNameError);
RUN_OUTPUT = 0;
}
if (email == null || email == "") {
var emailError = "Email is not valid";
var printEmailError = document.createTextNode(emailError);
var emailLabel = document.getElementById("emailError");
emailLabel.appendChild(printEmailError);
RUN_OUTPUT = 0;
}
if (areaCode == null || areaCode == "" || prefix == null || prefix == "" || suffix == null || suffix == "") {
var phoneError = "Area Code is not valid";
var printPhoneError = document.createTextNode(phoneError);
var phoneLabel = document.getElementById("phoneError");
phoneLabel.appendChild(printPhoneError);
RUN_OUTPUT = 0;
}
if (address == null || address == "") {
var addressError = "Address is not valid";
var printAddressError = document.createTextNode(addressError);
var addressLabel = document.getElementById("addressError");
addressLabel.appendChild(printAddressError);
RUN_OUTPUT = 0;
}
if (city == null || city == "") {
var cityError = "City is not valid";
var printCityError = document.createTextNode(cityError);
var cityLabel = document.getElementById("cityError");
cityLabel.appendChild(printCityError);
RUN_OUTPUT = 0;
}
if (fullState == null || fullState == "") {
var stateError = "State is not valid";
var printStateError = document.createTextNode(stateError);
var stateLabel = document.getElementById("stateError");
stateLabel.appendChild(printStateError);
RUN_OUTPUT = 0;
}
if (zip == null || zip == "") {
var zipError = "Zip is not valid";
var printZipError = document.createTextNode(zipError);
var zipLabel = document.getElementById("zipError");
zipLabel.appendChild(printZipError);
RUN_OUTPUT = 0;
}
if (genderChoice == null || genderChoice == "") {
var genderError = "Gender is not valid";
var printGenderError = document.createTextNode(genderError);
var genderLabel = document.getElementById("genderError");
genderLabel.appendChild(printGenderError);
RUN_OUTPUT = 0;
}
if (courseChoice == null || courseChoice == "") {
var courseError = "No Courses!";
var printCourseError = document.createTextNode(courseError);
var courseLabel = document.getElementById("courseError");
courseLabel.appendChild(printCourseError);
RUN_OUTPUT = 0;
}
if (Boolean(RUN_OUTPUT) != false) {
document.getElementsByClassName("errorField").textContent = "";
runOutputForm(div, name, address, city, fullState, zip,
email, areaCode, prefix, suffix, genderChoice,
courseChoice);
}
}
function runOutputForm(div, name, address, city, fullState, zip,
email, areaCode, prefix, suffix, genderChoice,
courseChoice) {
function br() {
return document.createElement('br');
}
var printName = document.createTextNode("Name: " + name + " ");
var printEmail = document.createTextNode("Email: " + email + " ");
var printPhone = document.createTextNode("Phone: " + areaCode + "-" + prefix + "-" + suffix);
var printAddress = document.createTextNode("Address: " + address + " " + city + ", " + fullState.text + " " + zip);
var printGender = document.createTextNode("Gender: " + genderChoice);
var printCourses = document.createTextNode("Courses Taken: " + courseChoice + " ");
div.appendChild(br());
div.appendChild(printName);
div.appendChild(br());
div.appendChild(printEmail);
div.appendChild(br());
div.appendChild(printPhone);
div.appendChild(br());
div.appendChild(printAddress);
div.appendChild(br());
div.appendChild(printGender);
div.appendChild(br());
div.appendChild(printCourses);
div.appendChild(br());
var output = document.getElementById("output");
if (output) {
output.parentNode.replaceChild(div, output);
} else {
document.body.appendChild(div);
}
}
I would like for only the current accurate messages to appear, either errors or valid output, not both. My element-replacing logic seems to be off. I am not using jQuery or innerHTML for this project. Please advise.
jsFiddle