sum up user input with javascript - 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!

Related

How make Total cart without "location.reload();"

i have a problem
In my cart, i want to recalculta the amount total off quantity and price
without using
location.reload();
You can find here a bit of my code to understand how i created all my elements
let productLocalStorage = JSON.parse(localStorage.getItem("products"));
let cartItems = document.getElementById('cart__items');
/*This Function is here because of the unknown number of products in the cart **
**so i can reuse the creation of all elements if i need **
**All the JS elements have their own description to make the code more understandble*/
const cartProducts = (productStorage) => {
console.log(productStorage.product);
//------Create constant article who gonna contein all my elements------
let article = document.createElement('article');
article.classList.add('cart__item');
article.setAttribute( "data-id", productStorage.id);
let cartDivImg = document.createElement('div');
cartDivImg.classList.add('cart__item__img');
let cartImg = document.createElement('img');
cartImg.setAttribute('src', productStorage["imageUrl"]);
cartImg.setAttribute('alt', productStorage["alt"]);
let cartDivContent = document.createElement('div');
cartDivContent.classList.add('cart__item__content');
let cartDivContentTitle = document.createElement('div');
cartDivContentTitle.classList.add('cart__item__content__titlePrice');
let cartName = document.createElement('h2');
cartName.textContent = productStorage.name;
let cartColorName = document.createElement('h2');
cartColorName.textContent = productStorage.color;
let cartPrice = document.createElement('p');
cartPrice.textContent = productStorage.price + " €";
let cartDivSettings = document.createElement('div');
cartDivSettings.classList.add('cart__item__content__settings');
let cartDivQuantity = document.createElement('div');
cartDivQuantity.classList.add('cart__item__content__settings__quantity');
let cartQuantityP = document.createElement('p');
cartQuantityP.textContent = "Qté : ";
let cartQuantityInput = document.createElement('input');
cartQuantityInput.setAttribute("type","number");
cartQuantityInput.setAttribute("name","itemQuantity");
cartQuantityInput.classList.add('itemQuantity');
cartQuantityInput.setAttribute("min","1");
cartQuantityInput.setAttribute("max","100");
cartQuantityInput.setAttribute("value", productStorage.quantity);
let cartItemDelete = document.createElement('div');
cartItemDelete.classList.add('cart__item__content__settings__delete');
let CartDeleteP = document.createElement('p');
CartDeleteP.textContent = "Supprimer";
CartDeleteP.classList.add('deleteItem');
//Create all the elements
article.appendChild(cartDivImg);
cartDivImg.appendChild(cartImg);
article.appendChild(cartDivContent);
cartDivContent.appendChild(cartDivContentTitle);
cartDivContentTitle.appendChild(cartName);
cartDivContentTitle.appendChild(cartColorName);
cartDivContentTitle.appendChild(cartPrice);
cartDivContent.appendChild(cartDivSettings);
cartDivSettings.appendChild(cartDivQuantity);
cartDivQuantity.appendChild(cartQuantityP);
cartDivQuantity.appendChild(cartQuantityInput);
cartDivSettings.appendChild(cartItemDelete);
cartItemDelete.appendChild(CartDeleteP);
cartItems.appendChild(article);
}
if (productLocalStorage === null){
emptyCart();
}
// Loop "forEach" who create all the elements i need in my cart
else{
productLocalStorage.forEach(productLocalStorage => {
cartProducts(productLocalStorage);
});
}
let products = JSON.parse(localStorage.getItem("products"));
function removeItem() {
let removeBtn = document.querySelectorAll(".deleteItem");
for (let i = 0; i < removeBtn.length; i++) {
removeBtn[i].addEventListener("click", (event) => {
event.preventDefault();
let articleSupp = removeBtn[i].closest("article");
articleSupp.remove();
calculateTotal();
totalArtQte();
deleteItemSelected(i);
alert("This item will be delete from your cart !");
location.reload();
// Actualising the total amount of item in the cart
});
//This Function is here to remove my item in my local storage
function deleteItemSelected(index) {
products.splice(index, 1);
localStorage.setItem("products", JSON.stringify(products));
}
}
}
And here is my remove function
as you can see, i try to recall my calculateTotal() and my totalArtQte() function
to recalculate the amount total off quantity and price, but my function are only recall
if i use location.reload(); is it normal ? Do you know what can i do ?
I have to use only JavaScript
Thank you for those who gonna read / answer to my question
you don't have to call whole thing again or location.reload(). try to find the events when you want to re-calculate the cart. e.g. on
new item add
updated existing quantity
delete items
function getProductById(id) {
let index = productLocalStorage.findIndex( x => x.id == id );
return productLocalStorage[index];
}
// on new item
function addProduct(product) {
cartProducts(product);
productLocalStorage.push(product);
// update your cart total/whatever by looping through "productLocalStorage"
}
// on quantity change
cartQuantityInput.addEventListener('change', function($event) {
let product = getProductById(productStorage.id);
product.quantity = $event.target.value;
// update your cart total/whatever by looping through "productLocalStorage"
});
// on delete
let deleteButton = document.createElement('button');
deleteButton.innerHTML = 'Delete';
deleteButton.addEventListener('click', function deleteProductEvent($event) {
productLocalStorage = productLocalStorage.filter(function( product ) {
return product.id !== $event.target.parentElement.getAttribute('data-id');
});
this.removeEventListener('click', arguments.callee, false);
$event.target.parentElement.remove();
// update your cart total/whatever by looping through "productLocalStorage"
});
PS: make sure your UI, "productLocalStorage" variable and localstorage are in sync.
this will be much easier if you implement this with MVC/MVVM framework like Angular

Input File Processing

I have a piece of code that is working....it allows me to display multiple files in a list when a user clicks on Choose File. The code works fine. However, I am trying to figure out if it's possible to append to the list instead of creating a new one each time. I've researched this most of the afternoon and a vast majority of the articles say it's not easily done. Should I be using a FormData approach instead? Would that buy me anything?
Here is my Javascript code...It works fine...
window.onload = function() {
const inputElement = document.getElementById("my_files");
const fileNames = document.getElementById("file_names");
let fileList = [];
function removeFile(event) {
event.preventDefault();
let filename = this.dataset.filename;
let modifiedFileList = new DataTransfer();
for (let i = 0; i < fileList.length; i++) {
if (fileList[i].name !== filename) {
modifiedFileList.items.add(fileList[i]);
}
}
inputElement.files = modifiedFileList.files;
fileList = inputElement.files;
handleFiles(fileList);
return false;
}
inputElement.addEventListener("change", handleFilesListener, false);
function handleFilesListener() {
fileList = this.files;
handleFiles(fileList);
}
function handleFiles(fileList) {
fileNames.textContent = '';
for (let i = 0; i < fileList.length; i++) {
let listElement = document.createElement("li");
let textNode = document.createTextNode(fileList[i].name);
listElement.appendChild(textNode);
listElement.setAttribute("class","attachmentname");
let removeButton = document.createElement("button");
removeButton.innerHTML = "Remove&nbsp";
removeButton.setAttribute('type', 'button')
removeButton.setAttribute("class", "button121");
removeButton.setAttribute('data-filename', fileList[i].name)
removeButton.addEventListener('click', removeFile)
listElement.appendChild(removeButton);
fileNames.appendChild(listElement);
}
}
}
Again, I'm trying to figure out if I can append to this list instead of constantly looping through it if the list changes. I did try to do an append instead of add below...but that didn't work. I'm a self proclaimed newb...so please go easy on me. :).
let filename = this.dataset.filename;
let modifiedFileList = new DataTransfer();
for (let i = 0; i < fileList.length; i++) {
if (fileList[i].name !== filename) {
modifiedFileList.items.add(fileList[i]);
}
}
Thanks in advance for any pointers.

Generate heading IDs based on text content, incrementing by 1 for every duplicate

I'm currently building an auto-generated TOC in Javascript. Step 1 is to take the text content of every h1-6, strip punctuation and spaces, replace with dashes, and lowercase it, then add that as the id, which is what I have here:
function TOC() {
let h2s = document.querySelectorAll("h2");
let h3s = document.querySelectorAll("h3");
let h4s = document.querySelectorAll("h4");
let h5s = document.querySelectorAll("h5");
let h6s = document.querySelectorAll("h6");
let headings = [...h2s, ...h3s, ...h4s, ...h5s, ...h6s];
function cleanID(content) {
let trimmed = content.trim();
let removedPunctuation = trimmed.replace(/[^\w\s]|_/g, "").replace(/\s+/g, " ");
let singleSpacesOnly = removedPunctuation.replace(/\s\s+/g, " ");
let spacesToHyphens = singleSpacesOnly.replace(/\W/g, "-");
let cleanedID = spacesToHyphens.toLowerCase();
return cleanedID;
}
headings.forEach((heading) => {
heading.id = cleanID(heading.textContent);
});
}
TOC();
This works fine except when it comes to duplicate IDs. What I'd like to do is increment by 1 for every duplicate of each heading, and append that. So for example, if I had
<h2>Foo</h2>
<h3>Bar</h3>
<h2>Foo</h2>
<h3>Baz</h3>
<h4>Bar</h4>
I'd like for the IDs to be, respectively, foo, bar, foo-2, baz, bar-2.
The obvious doesn't seem to work:
var cleanedIDs = [];
function cleanID(content) {
...
let increment = 0;
if(cleanedIDs.includes(cleanedID) {
cleanedID = `${cleanedID}-${increment++}`;
cleanedIDs.push(cleanedID);
} else {
cleanedIDs.push(cleanedID);
}
}
Would appreciate help working through the logic of it. I've started a pen here.
You can use reduce to keep track of the count inside an Object. Then just change the id property accordingly.
let headings = [...document.querySelectorAll("h3")];
function headingDups (headings) {
return headings.reduce((store, heading) => {
store[heading.textContent] = (store[heading.textContent] || 0) + 1;
if(store[heading.textContent] > 1) {
heading.id = heading.textContent + "-" + store[heading.textContent]
return store;
}
heading.id = heading.textContent;
return store;
}, {});
}
headingDups(headings);
<h3>hello</h3>
<h3>goodbye</h3>
<h3>h3llo</h3>
<h3>hello</h3>
<h3>h3llo</h3>
<h3>goodbye</h3>

How to display a score count, displaying times it has been randomly generated?

I'm making a text 'game', which has 3 players, whose names are in an array and I'm trying to set up a score count so that each time their name is randomly generated after pressing a button, it is added to their personal score count.
As this is my first project I haven't had any success on any methods.
var playerOne = prompt("Enter the name of the 1st player");
var playerTwo = prompt("Enter the name of the 2nd player");
var playerThree = prompt("Enter the name of the 3rd player");
const playerName = [playerOne, playerTwo, playerThree];
const didHow = ['quietly', 'carefully', 'slowly', 'quickly', 'secretly', 'ragefully'];
const didWhat = ['went', 'ran', 'fell', 'drove', 'jumped', 'fought', 'died'];
const quoteBtn = document.querySelector('#quoteBtn');
const playerNameQ = document.querySelector('#playerName');
const didHowQ = document.querySelector('#didHow');
const didWhatQ = document.querySelector('#didWhat');
quoteBtn.addEventListener('click', displayQuote);
function displayQuote() {
let numberOne = Math.floor(Math.random()*playerName.length);
let numberTwo = Math.floor(Math.random()*didHow.length);
let numberThree = Math.floor(Math.random()*didWhat.length);
playerNameQ.innerHTML = playerName[numberOne];
didHowQ.innerHTML = didHow[numberTwo];
didWhatQ.innerHTML = didWhat[numberThree];
}
Javascript is not a compiled language and is interpreted. I.e., order of declarations matter. This is less true when you get into classes, but for your example specifically, move your function declaration before you use it:
...
function displayQuote() {
// ...
}
quoteBtn.addEventListener('click', displayQuote);
Create an array of objects for each user,
arrUsers=[{
"id":"1"
"user":"user1",
"score":0
},{
"id":"2"
"user":"user2",
"score":0
},{
"id":"3"
"user":"user3",
"score":0
}]
After this, check the turn of the player with the id, and each time it press the button do score++.
I fixed the issue by putting:
var pointsOne = 0;
var pointsTwo = 0;
var pointsThree = 0;
before displayQuote() and by inserting the following code in the function:
if (playerName[numberOne] == playerOne) {
pointsOne++;
pointsOnee.innerHTML = pointsOne;
}
else if (playerName[numberOne] == playerTwo) {
pointsTwo++;
pointsTwoo.innerHTML = pointsTwo;
}
else if (playerName[numberOne] == playerThree){
pointsThree++;
pointsThreee.innerHTML = pointsThree;
}

Insert string to div on button click and clear it before next click

I try to create function which after click button, get string from user (from input) and spell it into div. It works, but only one time. When I change the string and click another one to button, page remember previous entered string.
I have tried to clear div and array before new iterating, but without success.
button.addEventListener('click', spell);
function spell(event) {
event.preventDefault();
let newArr = [];
for (let i=0; i<userText.length; i++) {
newArr.push(userText[i]);
}
programText.textContent = newArr;
}
How to clear an array to avoid this problem?
If you want to clear userText after you spell it, you can use userText.length = 0:
function spell(event) {
event.preventDefault();
let newArr = [];
for (let i=0; i<userText.length; i++) {
newArr.push(userText[i]);
}
userText.length = 0;
programText.textContent = newArr;
}
You don't even need to copy userText into newArr:
function spell(event) {
event.preventDefault();
programText.textContent = userText;
userText.length = 0;
}
Full code to this:
I have tried to clearing an array using: newArray = [] and newArray.length = 0. And clearing programText using programText.textContent = '' and programText.length = 0;
HTML
<article class=proj001Up>
<button class="button">Function 01</button>
<p>Spell the string</p>
</article>
<article class="proj001Down">
<input class="userText" type="text" name="userText" placeholder="Enter your string/word">
<article class="programText" placeholder="Result"></article>
JS
const button = document.querySelector('.button');
let userText = document.querySelector('.userText').value;
let programText = document.querySelector('.programText');
button.addEventListener('click', spell);
function spell(event) {
event.preventDefault();
let newArr = [];
for (let i=0; i<userText.length; i++) {
newArr.push(userText[i]);
}
programText.textContent = newArr;
}
Ok, I found the problem. I have to only delete value from let userText = document.querySelector('.userText'); and enter value to body of function. The correct version, below.
Thank you everybody for help :)
const button = document.querySelector('.button');
let userText = document.querySelector('.userText');
let programText = document.querySelector('.programText');
button.addEventListener('click', spell);
function spell(event) {
event.preventDefault();
let newArr = [];
for (let i=0; i<userText.value.length; i++) {
newArr.push(userText.value[i]);
}
programText.textContent = newArr;
}

Categories

Resources