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>
1
  • where is JQuery? this problem is easily solved by JQuery Commented Sep 14, 2015 at 11:08

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

Comments

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

5 Comments

This is not the case for html5: w3.org/TR/html5/dom.html#the-id-attribute says html only needs any 1 character.
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
yes i m writing the full code. and testing it again and posting a modified version in a minute
HTML 4.0 does restrict IDs to starting with a letter. stackoverflow.com/questions/70579/…
but i think HTML5.0 is what we are discussing

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.