Search code examples
javascriptsumuser-input

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.


Solution

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