1

I am learning Javascript and currently having an issue creating an application. I want to create a webpage that will take the values entered in a textbox, and place them inside an array. Then, I want to create a function that will add the values together. I am nearly complete, but I am having a tough time figuring out how to create a function that will add together the array items. My biggest issue is that any number of values can be entered into the page, and all the documentation I can find is based on having a pre-set array. Here is my code:

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Numbers</title>
</head>
<body>
    <section>
        <header class="header m-2" id="myForm">Numbers App</header>
        <section class="row m-2">
            <label class="inputLabel">Number: <input type="number" id="numInput"></label>
        </section>
        <button class="button m-1" onclick="displayText(); addNum(); testCount();" id="addButton">Add Number</button>
        <button class="button m-1" disabled>Calculate</button>
        <button class="button m-1" onclick="resetPage();">Reset</button>
    </section>

    <section id="numForm">
        <div class="numLabel m-2" id="numLabel">Numbers Added: </div>
        <p class="m-2 mt-3" id="numValue"></p>
    </section>

<script src="script.js"></script>
</body>
</html>
JS:
//Display "Numbers Added: " 
function displayText() {
    document.getElementById("numLabel").style.display = "block";
}

//Add the entered values into the array
let numArray = [];
function addNum() {
    let num = document.getElementById("numInput").value;

    numArray.push(num);
    document.getElementById("numValue").innerHTML = numArray.join(" ");
}

//Testing count function
function testCount() {
    for(count = 0; count > 2; count++) {
        console.log("this works");
    }
}

//Reset the page
function resetPage() {
    //Clear input field
    document.getElementById("numInput").value = "";
    //Hide "Numbers Added: "
    document.getElementById("numLabel").style.display = "none";
    //Clear array items
    numArray = [];
    document.getElementById("numValue").innerHTML = "";
}
Acuff558
  • 59
  • 8
  • You have the right idea; however, you are passing strings to your array. Instead of numArray.push(num), try numArray.push(parseInt(num)) . Afterward, when you trigger that calculate button, then take that numArray and use a simple for loop to add it all together then display it will innerhtml. – ousecTic Mar 07 '20 at 02:32
  • Thanks to the helpful comments, I am SUPER close to getting where I want to be with the following function : – Acuff558 Mar 07 '20 at 02:45
  • function arraySum() { var result = numArray.reduce((acc, curr) => parseInt(curr) + parseInt(acc), 0); document.getElementById("numValue").innerHTML = numArray[1] + " + " + numArray[2] + " = " + result; } – Acuff558 Mar 07 '20 at 02:46
  • However, my biggest issue is still that the array is not pre-defined. I can call on array elements by "numArray[1]", but any number of integers can be entered into the textbox, so I can't just string them together like that. I need to find a way to create this calculation for any number of array elements – Acuff558 Mar 07 '20 at 02:48

3 Answers3

1

Edit: To display the addition can just use something like:

const array1 = [1, 2, 3, 4];
const result = array1.reduce((acc, curr) => parseInt(curr) + parseInt(acc));

let additionDisp = array1.join(" + ") + " = " + result;
console.log(additionDisp);
pedro-hdt
  • 11
  • 1
  • 5
  • My bad, looking back I definitely could have worded this better. I currently have a button "Add Number" that adds the value of the textbox into my array. I am wanting to make a second button "Calculate" that will take the values entered into the array, and add them together. I also want it to display the numbers being added together. For example, if i entered in 5 and 10, I would want the calculate button to show: "Numbers Added: 5 + 10 = 15". Hopefully this explanation is a little more understandable. – Acuff558 Mar 07 '20 at 02:35
  • see the answer below then – pedro-hdt Mar 07 '20 at 03:08
0

You need to declare your add function first, parse your string input to integer value and perform a reduction to get the sum

//Add the entered values into the array
let numArray = [];

//Display "Numbers Added: " 
function displayText() {
  var result = numArray.reduce((acc, curr) => parseInt(curr) + parseInt(acc), 0);
  var numSumString = "";
  for (data of numArray) {
    numSumString = data + " + " + numSumString;
  }
  document.getElementById("numLabel").innerHTML = "Numbers Added:" + numSumString.substring(0, numSumString.length - 2) + "=" + result;
}

function addNum() {
  let num = document.getElementById("numInput").value;
  numArray.push(num);
  document.getElementById("numValue").innerHTML = numArray.join(" ");
}


//Reset the page
function resetPage() {
  //Clear input field
  document.getElementById("numInput").value = "";
  //Hide "Numbers Added: "
  document.getElementById("numLabel").style.display = "none";
  //Clear array items
  numArray = [];
  document.getElementById("numValue").innerHTML = "";
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Numbers</title>
</head>

<body>
  <section>
    <header class="header m-2" id="myForm">Numbers App</header>
    <section class="row m-2">
      <label class="inputLabel">Number: <input type="number" id="numInput"></label>
    </section>
    <button class="button m-1" onclick="addNum();" id="addButton">Add Number</button>
    <button class="button m-1" onclick="displayText();">Calculate</button>
    <button class="button m-1" onclick="resetPage();">Reset</button>
  </section>

  <section id="numForm">
    <div class="numLabel m-2" id="numLabel">Numbers Added: </div>
    <p class="m-2 mt-3" id="numValue"></p>
  </section>

  <script src="script.js"></script>
</body>

</html>
Sunil Lama
  • 4,531
  • 1
  • 18
  • 46
  • Hi, this is super helpful, but not quite what I'm going for. I definitely should've worded my question better. I currently have a button "Add numbers" that adds the value of the textbox into my array as an array item. I am wanting to make a second button "calculate" that will take the array items, and add them together. I also want it to display the calculation. For example, if I typed in a 5 and then a 10, I would want the calculate button to show the following HTML: "5 + 10 = 15". Again, thank you for your time and help, hopefully this clarifies things a bit better. – Acuff558 Mar 07 '20 at 02:38
  • @Acuff558, just change the logic a bit like above. see the edited code – Sunil Lama Mar 07 '20 at 02:55
  • Thank you! This is awesome and works perfectly. I did not know about the subString property, but I am going to do some more research into it now. – Acuff558 Mar 07 '20 at 03:07
  • 1
    @Acuff558, mark it as correct, if it solved for you. thanks – Sunil Lama Mar 07 '20 at 03:35
0

Use Array.prototype.reduce.

const array = [0, 42, 101, 5, 2];
const total = array.reduce((sum, x) => sum + x);

console.log(total);
Rúnar Berg
  • 4,229
  • 1
  • 22
  • 38