0

I am trying to add these two numbers for an hour and can't get the result in the third text field. Please help me achieve this. thank you. also please tell me is there any add() method in javascript?

<!DOCTYPE html>
<html>
<head>
    <title>test</title>
<style type="text/css">
    #cal{
        border:3px solid green;
        padding: 5px;
        width:250px;
        text-align: center;
    }

</style>
</head>

<body>
    <button onclick="add()" id="button">Add</button>
    <div id="cal">
    <input type="text" value=" " id="num1" size="5">
    +
    <input type="text" value=" " id="num2" size="5">
    =
    <input type="text" value=" " id="sum" size="5"> 
    </div>
<script>
        function add()
    {
        var a = document.getElementById("num1").value;
        var b = document.getElementById("num2").value;
        var ans =  a + b ;
        document.getElementById("sum").value = ans;
    }
</script>

</body>
</html>
2
  • they aren't numbers they are strings until you convert to number. There are a wide variety of ways to convert. Commented Dec 21, 2014 at 19:04
  • That's what I call a typical JavaScript beginner problem. Don't worry, every JS developer had this problem once. Commented Dec 21, 2014 at 19:04

2 Answers 2

1

The input values are strings not numbers. You have to convert them to numbers with the function parseInt() for integers or parseFloat() if they happen to be decimal numbers :

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

5 Comments

what if they are decimal?
You use parseFloat instead of parseInt
You left out the radix; was that deliberate?
@Teemu that comment was made when answer was using parseInt
@Teemu: no, but parseInt() does; which was used in the original answer (edited in the grace period).
1

Check this demo

Use JavaScript Number() Function

function add(){
    var a = document.getElementById("num1").value;
    var b = document.getElementById("num2").value;
    var ans =  Number(a) + Number(b) ;
    document.getElementById("sum").value = ans;
}

Comments

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.