0

In my code can add number array and show result in text field, but after i add new number and try to get sum of number in array it concatenates( e.g. 5+5=10, but it returns 5+5=55). It is first time i touched this problem, how can i handle this? See code plz:

<!DOCTYPE html>
<html>
<head>
  <title>Title of the document</title>
  <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
  <input type="text" id="n1"/><br/><br/>
  <input type="text" id="n2"/><br/><br/>
  <button id="buttoni">Get Aray Sum</button>
  <button id="buttona">Add Array</button>
  <p id="pText"></p>
</body>
 <script>
        let btnGet = document.getElementById("buttoni");
        let result = document.getElementById("n2");
        
        let numbers =  [];

        document.getElementById("buttona").onclick = function pushData()
            {
                // get value from the input text
                var inputText = document.getElementById('n1').value;
                
                // append data to the array
                numbers.push(inputText);
                
                var pval = "";
                
                for(i = 0; i < numbers.length; i++)
                {
                    pval = pval + numbers[i] + "<br/>";
                }
                // display array data
                document.getElementById('pText').innerHTML = pval;
            };
            let numo = numbers;
            btnGet.addEventListener('click', () => {
            result.value = numo.reduce((total, current) =>  total += current);
        });
  </script>
</html>

2 Answers2

1

convert it to integer first. parseInt(value);

Javascript thinks it as a string so it adds it just like any other string ("5" + "5" would be 55 while 5+5 or parseInt("5") + parseInt("5") would be 10)

Replace line 24 with var inputText = parseInt(document.getElementById('n1').value); or replace line 27 with numbers.push(parseInt(inputText));

Shiuki
  • 86
  • 5
  • You could also use Number(inputText) for fractional value support ;) ParseInt will error numbers like 1.3 etc, while Number will turn it into float. ParseInt("1.3") + ParseInt ("1.3") = nan, while Number(1.3) + Number(1.3) = 2.6 – Shiuki Jun 15 '21 at 08:39
  • (you should use number, unless you specifically want to use whole numbers) – Shiuki Jun 15 '21 at 08:44
0

Change below line

numbers.push(inputText);

with

numbers.push(parseInt(inputText));
Amit Verma
  • 2,450
  • 2
  • 8
  • 21