www.webdeveloper.com
Results 1 to 3 of 3

Thread: Javascript Times Table HELP! ! ! !

  1. #1
    Join Date
    Aug 2011
    Posts
    7

    Javascript Times Table HELP! ! ! !

    I need to create a times table using javascript. The user needs to input a number in a text field and when the button his hit it generates a times table into an HTML table. In column 1 it should display the number that was entered into the text field, column 2 should display the loop 1 to 10, and column 3 should display the answer.

    I know I need to use onclick, .innerHTML, and getElementById() but I am unsure how to get the results into the table. Please help! ! ! ! !

    Thanks

  2. #2
    Join Date
    Nov 2007
    Posts
    409
    Presuming you already have your math worked out...
    as you cycle through each "times" (x1, x2, x3, ...), you set the innerHTML of each table cell to the value.

    e.g.
    if "i" is the counter in your loop and "num" is what you are multiplying by, and each cell in your table has an id such as "ans1", "ans2", etc.:
    Code:
    ans = num * i
    document.getElementById('ans' + i).innerHTML = ans

  3. #3
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,356

    Lightbulb

    Alternative attempt ...
    Code:
    <!DOC HTML>
    <html>
    <head>
    <title> Multiplication Table </title>
    <script type="text/javascript">
    //<![CDATA[
    function multiplier() {
      var mult = document.getElementById('multipleOf').value;
      var str = '';
      str += '<table border="1" width="100%">';
      str += '<caption> Multiples of: '+mult+'</caption>';
      str += '<tr>';
      for (var i=0; i<10; i++) {
        str += '<td style="text-align:right">';
        str += ' X ' + i + ' = <br>';
        str += mult * i;
        str += '</td>';
      }
      str += '</tr>'
      str += '</table>';
      document.getElementById('multTable').innerHTML = '<h2>Multiplication Table</h2>'+str;
    }
    //]]>
    </script>
    
    </head>
    <body>
    <input type="text" id="multipleOf" value="">
    <button onclick="multiplier()">Multiplier Table</button>
    <div id="multTable"> <h2>Multiplication Table</h2> </div>
    </body>
    </html>

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles