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>

      

+3


source to share


6 answers


You can use the following:



z= +x + +y; // + is prefixed to convert input into number

      

+2


source


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.

+2


source


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);

+1


source


A quick way to convert a string to a number is to use the unary + operator.

z = +x + +y

      

or

z = parseInt(x) + parseInt(y);

      

+1


source


var x = parseInt(document.getElementById("inp1").value);

      

this will convert your "string" number to integer, also you can use parseFloat()

if you have floating point numbers

+1


source


You can use the following:

var x = document.getElementById("inp1").value*1;
var y = document.getElementById("inp2").value*1;

      

x at this moment there is a number !!

Cleaner for me !!!

+1


source







All Articles