且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么这个JavaScript和HTML代码不计算结果?

更新时间:2023-10-06 19:17:52

simply use parse the variable value to integer using parseInt() method or add "+"before to your variable name. Because variables var1 and var2 returning string. To calculate those variable values, you need to convert it as a integer.

using parseInt() method

number=parseInt(var1)+parseInt(var2)

use + before variable name to convert into integer,

number= +var1 + +var2

try this code,

<html>
    <body>
        <script>
        function myFunction(var1,var2){
            number = parseInt(var1) + parseInt(var2)
            //another way number= +var1+ +var2
            document.write(number)
        }
        </script>
    <form>
        Number 1 : <input type="text" name="no1"><br>
        Number 2 : <input type="text" name="no2"><br>
        <input type="button" onclick="myFunction(this.form.no1.value,this.form.no2.value)" value="submit">
    </form>

    <p id="demo"></p>

    </body>
</html>

using parseInt() DEMO

using + before variable name DEMO

相关阅读

推荐文章