简体   繁体   中英

Javascript: Simple addition program not working

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>

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> 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM