Search code examples
javascripthtmlcssforms

How to activate the reduce method with input value,


How to activate the reduce method with input value can anyone help with the modification or the idea

let catchvalue = document.querySelector("input");
let btn = document.querySelector("button");
btn.addEventListener(`click`, function(){
  let emptyarray = [10, 10];
  let totalvalue = emptyarray.unshift(catchvalue.value);
  let averagenumbers = emptyarray.reduce(function(acc, curr){
    return acc + curr;
    let extract = parseInt(emptyarray);
  });
});

Solution

    • NEVER call anything name or ID=submit in a form you want to process with JavaScript –
    • Nothing will execute after a return statement –
    • What do expect parseInt(emptyarray); would do? Did you want perhaps to do this? emptyarray.unshift(+catchvalue.value); –

    Here is my guess what you wanted

    let catchvalue = document.getElementById("Amount");
    let btn = document.getElementById("calc");
    let emptyarray = [10, 10];
    btn.addEventListener(`click`, function() {
      let totalvalue = emptyarray.unshift(+catchvalue.value);
      let total = emptyarray.reduce((acc, curr) => acc + curr);
      let avg = (total / emptyarray.length).toFixed(2);
      console.log("Average of", emptyarray, "'s total of", total, "is", avg)
    });
    <input type="text" id="Amount" class="Amount">
    <button type="button" id="calc">Calculate</button>