3

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>
Tushar
  • 78,625
  • 15
  • 134
  • 154
Manu Karki
  • 103
  • 2
  • 14

2 Answers2

2

The n in number should be uppercase. number should be Number.

Demo

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>
Tushar
  • 78,625
  • 15
  • 134
  • 154
2

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) ;
alamin
  • 1,791
  • 1
  • 22
  • 28
  • This is not the case for html5: http://www.w3.org/TR/html5/dom.html#the-id-attribute says html only needs any 1 character. – Johan Sep 14 '15 at 10:20
  • 1
    `There are no other restrictions on what form an ID can take; in particular, IDs can consist of just digits, start with a digit, start with an underscore, consist of just punctuation, etc.` From [specs](http://www.w3.org/TR/html5/dom.html#the-id-attribute) – Tushar Sep 14 '15 at 10:20
  • yes i m writing the full code. and testing it again and posting a modified version in a minute – alamin Sep 14 '15 at 10:22
  • 1
    HTML 4.0 *does* restrict IDs to starting with a letter. http://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html – ro͢binmckenzie Sep 14 '15 at 10:32
  • but i think HTML5.0 is what we are discussing – alamin Sep 14 '15 at 10:33