S.alhaider
S.alhaider

Reputation: 124

I can't do a simple calculator with javascript

i want to make a simple calculator that just sum two numbers

var num1 = Number(document.getElementById("n1").value);
var num2 = Number(document.getElementById("n2").value);

function sum() {
  var result = num1 + num2;
  console.log(result);
}
<input type="text" id="n1">
<input type="text" id="n2">
<button id="btn" onclick="sum();">Submit</button>
<script src="javascript.js"></script>

when i run it and add two values and press the button it returns 0 in the console

Upvotes: 0

Views: 1175

Answers (3)

razouq
razouq

Reputation: 101

you have to put the num1 and num2 variables into the sum function, because your script should read the num1 and num2 values each time you want to calculate the sum.

 function sum() {
      var num1 = Number(document.getElementById("n1").value);
      var num2 = Number(document.getElementById("n2").value);
      var result = num1 + num2;
      console.log(result);
    }

Upvotes: 0

sebostien
sebostien

Reputation: 111

You are actually storing the first value of the inputs, which defaults to 0.

Change the variables to references to the elements. Then access the values when the user presses the button.

var num1 = document.getElementById("n1");
var num2 = document.getElementById("n2");

function sum() {
  var result = parseInt(num1.value) + parseInt(num2.value);
  console.log(result);
}
<input type="text" id="n1">
<input type="text" id="n2">
<button id="btn" onclick="sum();">Submit</button>
<script src="javascript.js"></script>

Upvotes: 0

PM 77-1
PM 77-1

Reputation: 13334

In your code you retrieve values before they are changed by a user.

var num1 = document.getElementById("n1");
var num2 = document.getElementById("n2");

function sum() {
  var result = Number(num1.value) + Number(num2.value);
  console.log(result);
}
<input type="text" id="n1">
<input type="text" id="n2">
<button id="btn" onclick="sum();">Submit</button>
<script src="javascript.js"></script>

Upvotes: 5

Related Questions