Converting an object into numbers

Tags: ,



Hello again stack overflow! Another day another rookie question. I have been trying to create my own simple little calculator and so far I have been working on the add function. It is working without errors but its adding values as if they were strings. I have been trying to place Numbers() and parseInt() around different variables to try and make them into numbers so the addition will work, but so far no matter what I do they wont change from an Object. (I found this out with console.log(typeof variable)

Here is my code!

var input = document.querySelector(".input");
let previousInput = null;

function add(){     
    if(previousInput === null){
        document.querySelector(".output").innerHTML += input.value
        previousInput = input;
    } else {
      document.querySelector(".output").innerHTML = previousInput.value + input.value
      console.log(typeof input)
      console.log(typeof previousInput)
    }
}

    <input class="input" type="text"></div>
    <button type="button" onClick="add();">+</button>
    <div class="output"></div>

Answer

var input = document.querySelector(".input");
let previousInput = null;

function add(){     
    if(previousInput === null){
        document.querySelector(".output").innerHTML += input.value
        previousInput = parseInt(input.value);
    } else {
       document.querySelector(".output").innerHTML = previousInput + parseInt(input.value)
       previousInput += parseInt(input.value);
    }
}

I added some parseInt() to actually evaluate the values to int.

Warning: your previous code would just be able to add once the values and wouldn’t work after that you need to raise the value of previousInput as well after updating the .ouput element



Source: stackoverflow