Reputation: 103
I'm trying to create a program that'll add two numbers when clicked on a button.
However, it's not working, I am totally confused what's wrong. In this program user is supposed to enter 2 numbers and program gives user the sum on the click.
Here's the Code:
<html>
<body>
<p>For adding two numbers</p>
<button onclick="myFunction()">Calculate</button>
<br/>
<input type="text" placeholder="1st number" id="1st" name="txt1">
<br/>+
<br/>
<input type="text" placeholder="2nd number" id="2nd" name="txt2">
<p id="demo"></p>
<script>
function myFunction() {
var a = document.getElementById("1st").value;
var b = document.getElementById("2nd").value;
var c = number(a) + number(b);
document.getElementById("demo").innerHTML = c;
}
</script>
</body>
</html>
Upvotes: 3
Views: 720
Reputation: 2487
according to W3Schools
Definition and Usage The Number() function converts the object argument to a number that represents the object's value.
If the value cannot be converted to a legal number, NaN is returned.
The Syntax of Number() function :
Number(object)
Here object is provided. if nothing then returns zero
so in your code snippet
var c = number(a) + number(b) ;
you just change it with
var c = Number(a) + Number(b) ;
Upvotes: 2
Reputation: 87203
The n
in number
should be uppercase. number
should be Number
.
function myFunction() {
var a = document.getElementById("1st").value;
var b = document.getElementById("2nd").value;
var c = Number(a) + Number(b);
document.getElementById("demo").innerHTML = c;
}
<button onclick="myFunction()">Calculate</button>
<br/>
<input type="text" placeholder="1st number" id="1st" name="txt1">
<br/>+
<br/>
<input type="text" placeholder="2nd number" id="2nd" name="txt2">
<p id="demo"></p>
Upvotes: 2