javaScript JSON localstorage, user input, only saving first entry - javascript

I am busy doing an online boot camp, and only recently started learning JavaScript, I was also introduced to JSON in this task, the task I am currently busy with, must take user input and store it in local storage, and also display it on the webpage. The user should also be able to edit or delete data already saved (I haven't even gotten to that part yet), I am just trying to get the data to store.
I finally got the input to display, but it is not storing it to the localStorage. I have googled a lot and followed online tutorials.
Any help or advice will be greatly appreciated. I have included my JS file below.
let entry = document.getElementById("entry");
entry.addEventListener("click", displayDetails);
let row = 1;
function displayDetails() {
let title = document.getElementById("title").value;
let artist = document.getElementById("artist").value;
let album = document.getElementById("album").value;
let genre = document.getElementById("genre").value;
if (!title || !artist || !album || !genre) {
alert("Please fill all boxes");
return;
}
let display = document.getElementById("display");
let newRow = display.insertRow(row);
let cell1 = newRow.insertCell(0);
let cell2 = newRow.insertCell(1);
let cell3 = newRow.insertCell(2);
let cell4 = newRow.insertCell(3);
cell1.innerHTML = title;
cell2.innerHTML = artist;
cell3.innerHTML = album;
cell4.innerHTML = genre;
row++;
}
displayDetails = (ev) => {
ev.preventDefault(); //to stop the form submitting
let song = {
title: document.getElementById("title").value,
artist: document.getElementById("artist").value,
album: document.getElementById("album").value,
genre: document.getElementById("genre").value,
}
entry.push(entry);
document.querySelector("form").reset();
let pre = document.querySelector("#msg pre");
pre.textContent = '\n' + JSON.stringify(entry, '\t', 2);
localStorage.setItem("MySongList", JSON.stringify(entry));
}
document.addEventListener("DOMContentLoaded", () => {
});

Declare songList array outside function and push the song object into songList and then save it as string into localStorage as given in the below code snippet.
let entry = document.getElementById("entry");
entry.addEventListener("click", displayDetails);
let row = 1;
const songList = [];
function displayDetails() {
// your code......
const song = {
title: document.getElementById("title").value,
artist: document.getElementById("artist").value,
album: document.getElementById("album").value,
genre: document.getElementById("genre").value,
}
songList.push(song);
// your code......
localStorage.setItem("MySongList", JSON.stringify(songList));
}

Related

js global array to table - show all the values in the array over and over again (duplicated in the table)

i need a global array that keep players details and inner into table but when I add a new player from a form, in the table i see duplicated values always. for example if i have [1], the table show 1, when i add some [1,2] for example, the table show 1,1,2 and if i add more, the table show to me 1,1,1,2,2,3
i work with real time database, with onValue to show the players in the table.
i want a global array and when i add one object its will add only this object to the table.
var playerslist = [];
function addplayertotable(name, age, number, rule){
let trowplayers = document.createElement("tr");
let tdplayername = document.createElement("td");
let tdplayerage = document.createElement("td");
let tdplayernumber = document.createElement("td");
let tdplayerrule = document.createElement("td");
tdplayername.innerHTML = name;
tdplayerage.innerHTML = age;
tdplayernumber.innerHTML = number;
tdplayerrule.innerHTML = rule;
trowplayers.appendChild(tdplayername);
trowplayers.appendChild(tdplayerage);
trowplayers.appendChild(tdplayernumber);
trowplayers.appendChild(tdplayerrule);
tbodyplayers.appendChild(trowplayers);
}
function addallitemstotable(theplayer){
tbodyplayers.innerHTML = "";
theplayer.forEach(element =>{
addplayertotable(element.PlayerName, element.PlayerAge, element.PlayerNum, element.PlayerRule);
});
}
function getplayersdata(){
auth.onAuthStateChanged(user =>{
if(user){
const dbRef = ref(database, 'players/' + user.uid);
onValue(dbRef, (snapshot) =>{
snapshot.forEach(childsnapshotplayer => {
playerslist.push(childsnapshotplayer.val());
});
addallitemstotable(playerslist);
})
}
else{
console.log("null")
}
})
}

sum up user input with javascript

I'm trying to store a user input in a variable and output it.
I actually thought it would be very easy, but right now I'm stuck on this task
I'm trying to store this in an array. but I would also be happy if it was simply stored in a variable and I could output it.
I've been searching for it for a long time, but I have the feeling that I don't know exactly what to look for
here is my code:
let inputValuePrice = document.getElementById("myInput2").value;
let outputSumme = document.getElementById("summe");
outputSumme = parseFloat(inputValuePrice);
let sum = [];
sum.push(outputSumme);
console.log(sum);
<input type="number" id="myInput2" />
<input type="text" id="summe" />
edit:
I'm sorry. I'll explain it again in more detail. I want to add the number after each entry. It is a kind of to-do list with products and prices. each product is entered one by one along with the price. I would then like to add up the price of each product. In this case it is enough for me if it is first output in the console. If it is correct then I will let it output to the html.
if you need to calculate the sum of all inputs values as an integer or a float number it's very simple. you can use a simple function to sums all of your array elements like this:
let inputValuePrice = document.getElementById("myInput2").value;
let outputSumme = document.getElementById("summe");
outputSumme = parseFloat(inputValuePrice);
let sum = [];
sum.push(outputSumme);
console.log(getSumOfArray(sum));
function getSumOfArray(array){
let sumOfElements=0;
for (let i=0;i<array.length;i++){
sumOfElements=sumOfElements+array[i];
}
return sumOfElements;
}
If your array elements are all numbers you can use the reduce operator as follows:
const sumOfArray = sum.reduce((a, b) => a + b, 0)
Unfortunately I don't understand how it works. I have now the products with prices in the indexedDB in my code. There I wanted to read them out and sum them up again in an array. I'll send you the whole code. I would be very grateful for an explanation. what is wrong with my thinking? Here is my code.
This snippet is in a function that when run puts the products in a list in the HTML. The products are created in a foreach loop and in that I intercept the prices and send them outside of the function to another function which then has the data to calculate with. I hope it is understandable. I'll link the whole code at the end of this thread.
let products = makeTransaction('produkte', "readonly");
let request = products.getAll();
request.addEventListener('success', (event) => {
event.preventDefault();
document.querySelector('#product-list').innerHTML = "";
let data = event.target.result;
data.forEach((element) => {
/*-----------Elemente Kreieren------------*/
let li = document.createElement("li");
let edit = document.createElement('i');
let spanPrimary = document.createElement('span');
let inputLabel = document.createElement('label');
let productName = document.createElement('span');
let productPrice = document.createElement('span');
let spanSecondary = document.createElement('span');
let checkBox = document.createElement('input');
let closeBtn = document.createElement("span");
/*-----------Elemente einfügen------------*/
li.setAttribute('data-key', element.id);
productName.appendChild(document.createTextNode(element.title));
productPrice.appendChild(document.createTextNode(element.price + " €"));
spanPrimary.appendChild(productName);
spanPrimary.appendChild(productPrice);
inputLabel.appendChild(checkBox);
spanSecondary.appendChild(inputLabel);
li.appendChild(edit);
li.appendChild(spanPrimary);
li.appendChild(spanSecondary);
li.appendChild(closeBtn);
/*-----------Elemente klassifizieren------------*/
li.className = "mdl-list__item mdl-shadow--2dp";
edit.className = "material-symbols-outlined icon-edit-document";
edit.textContent = 'edit_document';
spanPrimary.className = "mdl-list__item-primary-content";
spanSecondary.className = "mdl-list__item-secondary-action";
inputLabel.className = "mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect";
productName.className = 'product-text';
productPrice.className = 'product-preis';
checkBox.className = "mdl-checkbox__input";
checkBox.setAttribute('id', 'my-id');
checkBox.setAttribute('type', 'checkbox');
closeBtn.className = "material-symbols-outlined hiding-list-item";
closeBtn.textContent = 'close';
componentHandler.upgradeElement(li);
let list = document.getElementById("product-list").appendChild(li);
// Füge die "edit" Funtion hinzu
let editieren = document.getElementsByClassName("icon-edit-document");
for (let i = 0; i < editieren.length; i++) {
editieren[i].onclick = function() {
showProducts(element.id);
}
}
// Füge die "close" Button Funktion hinzu
let close = document.getElementsByClassName("hiding-list-item");
for (let i = 0; i < close.length; i++) {
close[i].onclick = function() {
deleteProduct();
}
}
// Function for totalizing product prices
let produktPreis = element.price
sumPrice(produktPreis);
});
});
request.addEventListener('error', (event) => {
console.log(event.target.error);
});
}
and now the summation...
function sumPrice(produktPreis) {
produktPreis = parseFloat(produktPreis);
let arr = [];
arr.push(produktPreis);
console.log(getSum(arr));
console.log(sumOfArray);
function getSum(array) {
let sumOfElements = 0;
for (let i = 0; i < arr.length; i++) {
sumOfElements = sumOfElements + array[i];
}
return sumOfElements;
}
}
I've always been able to help myself. But I can't get any further with this supposedly simple thing.
and for the completeness. Here is my temporarily hosted website and Github. Thanks also for the previous replies.
Project site
https://liquefied-stripe.000webhostapp.com/
Github
https://github.com/StevoEs/Einkaufsliste/blob/main/main.js
Thanks!

Google Apps Script add paragraph to Google Document in specific location based on date

I'm using Google Forms to create an easy method of adding stories and photos to a Google doc for a collective history/journal.
My code takes the Google form responses from the linked Google sheet and then just appends the Google Form responses to the Google doc but I would like to add the responses sorted by the date that gets submitted in the Google form. That way an event that gets submitted that took place on 01/01/2020 will be listed before an event that took place on 01/02/2020 etc.
How would I go about doing that?
function autoFillGoogleDocFromForm(e) {
var timestamp = e.values[0];
var photo = e.values[1];
var date = e.values[2];
var event = e.values[3];
var name = e.values[4];
var photoCap = e.values[6];
var photoDesc = e.values[7];
var fileURL = photo;
var fileID = fileURL.substr(fileURL.search("=")+1); //strip off text before id= in the URL
var image = DriveApp.getFileById(fileID).getBlob();
var doc = DocumentApp.openById("1DrE4ElgaP08uOTH52E2GjgmrJmoL2VZsZ1YlNeV0_20")
var body = doc.getBody();
body.appendPageBreak();
body.appendParagraph(date);
body.appendParagraph(event);
body.appendParagraph(name);
body.appendImage(image);
body.appendParagraph(photoCap);
body.appendParagraph(photoDesc);
doc.saveAndClose();
}
Here is an example of how to insert paragraphs based on date. I use Date object to compare dates so I convert a text string in the form "1/1/2022" to a Date object.
The format of your Doc must have the date string directly following the Page Break.
function testAutoFillGoogleDocFromForm() {
try {
let row = { values: [ "time", "photo", "2/1/2022", "event", "name", "", "photoCap", "photoDesc" ]};
autoFillGoogleDocFromForm(row);
console.log("done");
row = { values: [ "time", "photo", "1/1/2023", "event", "name", "", "photoCap", "photoDesc" ]};
autoFillGoogleDocFromForm(row);
console.log("done");
}
catch(err) {
console.log(err)
}
}
function autoFillGoogleDocFromForm(e) {
try {
let timestamp = e.values[0];
let photo = e.values[1];
let date = new Date(e.values[2]);
let event = e.values[3];
let name = e.values[4];
let photoCap = e.values[6];
let photoDesc = e.values[7];
let doc = DocumentApp.getActiveDocument();
let body = doc.getBody();
let i = 0;
while( i < body.getNumChildren() ) {
let para = body.getChild(i);
if( para.getType() === DocumentApp.ElementType.PARAGRAPH ) {
let j = 0;
console.log("numchild = "+body.getNumChildren());
while( j < para.getNumChildren() ) {
let child = para.getChild(j);
if( child.getType() === DocumentApp.ElementType.PAGE_BREAK ) {
// get next paragraph and check date
if( (i+1) >= body.getNumChildren() ) break; // in case there is a page break at the end of body
para = body.getChild(i+1);
let temp = new Date(para.asParagraph().getText());
console.log(temp);
if( temp > date ) {
body.insertPageBreak(i++);
body.insertParagraph(i++,date.toLocaleDateString());
body.insertParagraph(i++,event);
body.insertParagraph(i++,name);
body.insertParagraph(i++,photoCap);
body.insertParagraph(i++,photoDesc);
return;
}
}
j++;
}
}
i++;
}
// if the date is latest just append a new page
body.appendPageBreak();
body.appendParagraph(date.toLocaleDateString());
body.appendParagraph(event);
body.appendParagraph(name);
//body.appendImage(image);
body.appendParagraph(photoCap);
body.appendParagraph(photoDesc);
}
catch(err) {
console.log(err)
}
}

How to render python dictionary values in Javascript Fetch API (forEach)?

I am trying to render python dictionary values inside a Javascript Fetch API. I tried various ways to do so such as serializing values and using dictionary keys to access the dictionary values. I got no error message but the values I rendered are all "undefined" on my webpage.
Python
def portfolio_position(request):
positions = Portfolio.objects.filter(owner=request.user, off_portfolio=False).order_by('-symbol').values()
return JsonResponse([position for position in positions], safe=False)
Javascript
function load_portfolio_position() {
fetch('/portfolio_position')
.then(response => response.json())
.then(positions => {
console.log(positions);
var table = document.getElementById("portfolio-table");
positions.forEach(position => {
var row = table.insertRow(1);
row.id = `row_${position.symbol}`;
var symbol = row.insertCell(0);
var price = row.insertCell(1);
var change = row.insertCell(2);
var average_cost = row.insertCell(3);
var position = row.insertCell(4);
var pnl = row.insertCell(5);
var pnl_percent = row.insertCell(6);
symbol.innerHTML = `${position.symbol}`;
price.innerHTML = `${position.price}`;
change.innerHTML = `${position.change}`;
var avc = parseFloat(position.cost).toFixed(3);
average_cost.innerHTML = `${avc}`;
position.innerHTML = `${position.position}`;
pnl.innerHTML = `${position.pnl}`;
pnl_percent.innerHTML = `${position.pnl_percent}`;
});
})
}
Appreciate your help!

How to read values from a Firebase Database and store them into an HTML table

I have a Firebase Database that stores two values distance and a timestamp. I'm able to read the distances, but un able to read to more than 1 timestamp at a time.
for (var i = 0; i <= 10; i++) {
ref.child("distance").child(i).once("value").then(function(snapshot) {
test = snapshot.val();
test1 = JSON.stringify(test).replaceAll(/[^a-zA-Z0-9.]/g, "");
myCreateFunction(test1, i+"");
});
ref.child("time").child(i).once("value").then(function(snapshot) {
time1 = snapshot.val();
console.log(time1);
myCreateFunc(time1["0"], i+"");
});
}
function myCreateFunction(test1, i) {
var table = document.getElementById("myTable");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell2.id = i;
cell1.innerHTML = test1;
}
function myCreateFunc(time1, i) {
document.getElementById(i).innerHTML = time1;
}
This is a picture of my database
This is the picture of the error that we get on our webpage
I think you are only sending your first element of the array to the HTML create table:
myCreateFunc(time1["0"], i+"");
instead of something like this:
myCreateFunc(time1, i+"");
Let me know if this solved your problem!

Categories

Resources