After i reload i want to keep the local storage values - javascript

This is my function:
function render() {
let list = document.getElementById('myNotes');
trashFolderModal = document.getElementById('allBlur');
list.innerHTML = localStorage.setItem(key, text);
for (let i = 0; i < titles.length; i++) {
const title = titles[i];
const note = notes[i];
list.innerHTML += card(title, note, i);
}
}
And here is my Note Website (you can see the source code):
http://patrick-sterz.developerakademie.com/Notizblock2/index%282%29.html

setItem returns undefined.
I suspect you need to revisit what you want to do.
Normally we do this when the list changes
localStorage.setItem("list",JSON.stringify(myListArray));
and when we load the page we do a
let listContent = localStorage.getItem("list");
let myListArray = listContent ? JSON.parse(listContent) : [];

Related

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!

Create multiple HTML elements in for-loop from array

I want to create some HTML Elements of the same type with a for loop in JavaScript.
I wonder if I need to create a new Javascript variable for every element I want to show in the DOM or is it enought to override the same element again and again in my loop?
I wrote this code but it does only show one element as output:
let i;
for( i = 0; i < events.length; i++){
let tabElement = document.createElement("div");
tabElement.className = "tabElement";
tabElement.className = "ellipsis";
tabElement.id = "tabElement" + i;
tabElement.innerHTML = events[i].name;
let tabElementLink = document.createElement("a");
tabElementLink.className = "tabElementLink";
tabElementLink.id = "tabElementLink" + i;
$("tabElementLink").append(tabElement);
$(".tabBar").append(tabElementLink);
}
Than I wrote the following code but it this applies the same innerHTML to all returned elements.
let tabElements = {};
let tabElementsLink = {};
let i;
for( i = 0; i < events.length; i++){
tabElements['tabElement' + i] = document.createElement("div");
tabElements['tabElement' + i].className = "tabElement";
tabElements['tabElement' + i].className = "ellipsis";
tabElements['tabElement' + i].id = "tabElement" + i;
tabElements['tabElement' + i].innerHTML = events[i].name;
tabElementsLink['tabElementLink' + i] = document.createElement("a");
tabElementsLink['tabElementLink' + i].className = "tabElementLink";
tabElementsLink['tabElementLink' + i].id = "tabElementLink" + i;
tabElementsLink['tabElementLink' + i].append(tabElements['tabElement' + i]);
$(".tabBar").append(tabElementsLink['tabElementLink' + i]);
}
Which approach is right to generate multiple HTML elements from an array?
No metter, you can create every time new variable or rewrite. Better create variable every time.
your code can be optimized with new features and without any variables:
const events = [
{
name: "event1"
},
{
name: "event2"
},
{
name: "event3"
}
]
// if events is iterable
events.forEach((event, index)=>{
// for next lines, you forget href
$(".tabBar").append(`<div class="tabsElement ellipsis" id="tabelement${index}">${event.name}</div>`)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tabBar"></div>
And i don't think that you need any id at all, better to use data-id or something

Choosing the first post (loop)

I have a loop in Blogger that selects the last 5 posts.
I want to apply different css to the first of these last 5 posts and different css to the other 4 posts.
Current script applies same css to all of them, how can i keep first post separate.
Here is the script;
let postCount = 5;
function funcrct(JSON) {
const POSTS = JSON.feed.entry;
let postTitle, postUrl = "";
let rpc = document.querySelector(".postList");
for (let i = 0; i < postCount; i++) {
POSTS[i].link.forEach((el, i) => {
if (el.rel === "alternate") {
postTitle = el.title;
postUrl = el.href;
}
})
let thumbnail = POSTS[i].content.$t.match(/(http)?s?:?(\/\/[^"']*\.(?:webp))/)[0];
rpc.innerHTML += `<li>
<a href="${postUrl}"><figure>
<img src="${thumbnail}" alt="${postTitle}"/>
<figcaption>
${postTitle}</figcaption></figure></a>
</li>`;
}
}
var url = document.location.origin;
var fsrc = document.createElement("script");
fsrc.src = `${url}/feeds/posts/default?alt=json-in-script&start-index=1&max-results=${postCount}&callback=funcrct`;
document.body.appendChild(fsrc);
Html
<div><ul class='postList'></ul></div>

Update Array when new elements are displayed on webpage

I'm working on a chrome extension where I need to gather the total number of books in a library.
The code below works fine, however, the page where I'm getting the data only loads half of the books at once until you scroll down further and the array doesn't update accordingly.
Is there a way to automatically update the array to keep up with the changes?
let list = document.querySelectorAll("ul > li");
let numBooks = [];
for (let i = 0; i < list.length; i++) {
numBooks.push(i + 1);
}
console.log(numBooks);
// Variables
let list = document.querySelectorAll("ul > li");
let mlist = document.querySelector("ul");
let numBooks = [];
// Push books to array
for (let i = 0; i < list.length; i++) {
numBooks.push(i + 1);
}
// Observe changes
const observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
if (mutation.addedNodes.length) {
// Create Element: Book Count
let url = "myurl";
let nBooks = numBooks.length / 10;
let nChanges = mutation.addedNodes.length - 1;
if (url == window.location.href) {
let el = document.createElement("span");
el.innerHTML = nBooks + nChanges;
let par = document.getElementsByTagName("h2")[0];
par.appendChild(el);
}
}
});
});
observer.observe(mlist, {
childList: true,
});

Any ideas on what is wrong with this javascript code?

I have the code below. The purpose of the code is to grab all the values stored in the local storage and display them in two HTML elements with ids of 'title' and 'textLoc'. 'title' is an <input type="text"> and 'textLoc' is a <textarea>. I want the values to be stored in the <textarea> and the keys to be stored in the <input type="text">. The values are being stored correctly but the keys are not. Any ideas on why this would be?
var tests = [];
var titles = [];
var finalTests = "";
var key, value;
for (var i = 0; i < localStorage.length; i++) {
key = localStorage.key(i);
value = localStorage.getItem(key);
tests.push(value);
titles.push(key);
finalTests += "<tr><td><a class=\"dashlinks\" href=\"javascript:void\" onclick=\"rememberTest("+i+")\">" + key + "</a></td></tr>";
}
for (i=0; i<tests.length; i++) {
document.getElementById('title').innerHTML = titles[i];
document.getElementById('textLoc').innerHTML = tests[i];
}
You should use document.getElementById('title').value and document.getElementById('textLoc').value. Also it seems like you are doing nothing with finalTests after you store it.
You should be appending the string to the text area:
document.getElementById('title').innerHTML = document.getElementById('title').innerHTML + titles[i] + '\n';

Categories

Resources