Stevo Es
Stevo Es

Reputation: 51

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.

Upvotes: 0

Views: 523

Answers (3)

Stevo Es
Stevo Es

Reputation: 51

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!

Upvotes: 0

Rafael Zasas
Rafael Zasas

Reputation: 993

If your array elements are all numbers you can use the reduce operator as follows:

const sumOfArray = sum.reduce((a, b) => a + b, 0)

Upvotes: 0

hata.IR
hata.IR

Reputation: 87

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;
}

Upvotes: 1

Related Questions