skip to Main Content

I’m trying to make a simple calculator, however, when I try to add two numbers, I’m getting the NaN result.

Before this problem, the function sumar() was returning [object HTMLInputElement][object HTMLInputElement], however after adding + when calling the dom, it returns NaN.

HTML File

<body>
    <form>
        <div>
            <label for="op1">Ingrese un numero</label>
            <input type="number" value="0" id="op1"/>
        </div>
        <div>
            <label for="op2">Ingrese otro numero</label>
            <input type="number" value="0" id="op2"/>
        </div>
    </form>
    <div id="resultado">0</div>
    <button onclick="sumar()">Sumar</button>
    <script src="./script.js"></script>
</body>

JS file

const sumar = ()=> {
    const op1 = +document.getElementById("op1");
    const op2 = +document.getElementById("op2");
    document.getElementById("resultado").innerHTML = op1 + op2;
}

3

Answers


  1. Make sure you are not receiving string values . try using

      parseInt(op1)+parseInt(op2)
    
    Login or Signup to reply.
  2. You need to get the value of the elements

    const sumar = ()=> {
        const op1 = +document.getElementById("op1").value;
        const op2 = +document.getElementById("op2").value;
        document.getElementById("resultado").innerHTML = op1 + op2;
    }
    

    And parseInt() or parseFloat() to remove the error

    const sumar = ()=> {
        const op1 = +document.getElementById("op1").value;
        const op2 = +document.getElementById("op2").value;
        document.getElementById("resultado").innerHTML = parseFloat(op1) + parseFloat(op2);
    }
    
    Login or Signup to reply.
  3. In your javascript file, try to replace your code with this

    const sumar = () => {
       const op1 = document.getElementById("op1").value
       const op2 = document.getElementById("op2").value
       document.getElementById("resultado").innerHTML = parseInt(op1) + 
       parseInt(op2)
    }
    

    i’ve try in playcode.io, and that’s work well.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search