Search code examples
javascriptnanparseint

Javascript: why am i getting NaN even after using parseInt() function?


I want to create a HTML page that can do the following tasks:

  1. Take a number from the user
  2. Calculate a multiplication table and show it below the calculate button

Format of multiplication table should be like this, but on the same page and below the calculate button:

5
10
15
20
25
30
35
40
45
50

But I am getting NaN error, and also need help with how to get table displayed like this on the same page, please help and bear with my newbie mistakes :-)

<!doctype html>
<html>
    <head>
        <title>Multiplication Table</title>
        <script type="text/javascript">
            function createTable(nn)
            {
                for(i=1; i<=10; i++)
                { 
                    document.getElementById("t1").innerHTML = nn*i;
                }	
                return true;
            }
        </script>
    </head>
    <body>
        <h1><center>Assignment No.4</center></h1>
        <h4><center>Please Enter Number for Table and press the button</center><h4>
        <form>
            <center><input type="text" name="num" size=10></center><br />
            <center><button type="button" onclick="createTable('n')">Calculate</button></center>
        </form>
        <center><p id="t1"></p></center>
        <script type="text/javascript">
            m = "num".value;
            n = Number(m);
        </script>
        </body>
</html>


Solution

  • There some problem with your program just see this one

    <!doctype html>
    
    <html>
    <head>
    <title>Multiplication Table</title>
    <script type="text/javascript">
    function createTable()
    {
        var nn = document.getElementById("num").value;
    
        var str="<table>";
    
        for(i=1; i<=10; i++)
        { 
            str+="<tr><td>" + nn + "*" + i +" = " + (nn*i) + "</td></tr>";
        }
        str+="</table>";
    
        document.getElementById("t1").innerHTML = str;
    }
    </script>
    </head>
    
    <body>
    <h1><center>Assignment No.4</center></h1>
    <h4><center>Please Enter Number for Table and press the button</center><h4>
    
    <form>
    <center><input type="text" id="num" name="num" size=10></center><br />
    <center><button type="button" onclick="createTable()">Calculate</button></center>
    </form>
    <center><p id="t1"></p></center>
    </body>
    </html>