Add button not working in javascript
I made a simple calculator in javascript but the button +
doesn't work and it just shows the numbers next to it.
Here is my code:
<script>
function calc(operator) {
var x = document.getElementById("inp1").value;
var y = document.getElementById("inp2").value;
var z = 0;
switch (operator) {
case "+":
z = x + y;
break;
case "-":
z = x - y;
break;
case "*":
z = x * y;
break;
case "/":
z = x / y;
break;
}
document.getElementById("result").innerHTML=z;
}
</script>
source to share
Variables x
and y
contain strings. Divide them into numbers:
var x = parseFloat(document.getElementById("inp1").value);
var y = parseFloat(document.getElementById("inp2").value);
It happens that it works for other operators because there is no subtraction, multiplication or division for strings, it figures out that it has to convert strings to numbers.
source to share
var x=document.getElementById("inp1").value;
var y=document.getElementById("inp2").value;
returns the values in these text boxes as strings.
When you use the +
string operator , it will concatenate values. If you use the same operator for numbers, it will add values.
You will need to parse the textbox values into integer with a function parseInt
using one of the following methods.
var x=parseInt(document.getElementById("inp1").value);
var y=parseInt(document.getElementById("inp2").value);
and then do z=x+y;
I would recommend this because all operations, not just addition, will be done on integers.
or just change z=z+y;
to look likez = parseInt(x) + parseInt(y);
source to share