0

i have created a simple program in which it needs to add 1 and 3 and show 4 but it shows me 13 here is my program:

<html>
    <head>
        <style>
        </style>
        <script type="text/javascript">
        function calculate(){

            a = document.getElementById('num1').value;
            b = document.getElementById('num2').value;
            document.getElementById('result').innerHTML = a + b;
        }
        </script>
    </head>
    <body>
        <input id='num1' value="1"/>
        <input id='num2' value='3'/>
        <p id='result'></p>
        <button onclick="calculate()">Calculate</button>
    </body>
</html>

What do i do now?

2
  • 1
    It would be evident that your code is concatenating two variables rather than adding as intended. Concatenation is an operation performed on string objects, whereas addition is an operation performed on numeric objects. What do you think needs to happen for both string variables to treat them as numeric? Commented Apr 5, 2015 at 15:20
  • 2
    i recomend to declare your varibles after assigning a value, i mean: var a = ... Commented Apr 5, 2015 at 15:26

3 Answers 3

2

That's because value attribute returns a String. You need to convert it to a Number.

There's a shortcut though, by using + unary operator. You can also wrap the string in Number like Number(a) + Number(b).

a = +document.getElementById('num1').value;
b = +document.getElementById('num2').value;
Sign up to request clarification or add additional context in comments.

Comments

2

You have to convert to integer. Check out this code.

    function calculate(){

        a = parseInt(document.getElementById('num1').value, 10);
        b = parseInt(document.getElementById('num2').value, 10);
        document.getElementById('result').innerHTML = a + b;
    }

Comments

1

Try doing this:

document.getElementById('result').innerHTML =  parseInt(a) + parseInt(b);

The reason is because you a and b are strings and you need first to convert then to numbers.

1 Comment

It's a bad idea to ignore the radix.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.