1

I'm just trying to create simple javascript function that outputs a small table but can't seem to get it working.

<html>
<head>
    <meta charset ="utf-8">
    <title>Test Table</title>
    <script type = text/javascript>

        function drawTable()
        {
            var tableDiv = document.getElementById( "numbersTable" );

            tableDiv.innerHTML = "<table>" + 
            "<caption>Numbers Table</caption>" +
            "<thead><th>Number</th><th>Square</th><th>Cube</th></thead>" +
            "<tbody><tr><td>1</td><td>2</td><td>3</td></tr>" +
            "</tbody></table>";
        }

    </script>
</head>
<body>
<div id = "numbersTable"></div>
</body>

Can anyone see where the problem is?

5
  • 2
    Where are you calling drawTable() from? Commented Feb 10, 2013 at 21:28
  • Also remove the spaces between id = "numbersTable" - it's not a valid XML/HTML Commented Feb 10, 2013 at 21:30
  • I'm not sure but js don't like new lines for string merging. You should use string+="<table>"; instead. Also you should call drawTable() somewhere Commented Feb 10, 2013 at 21:33
  • @Anthony it does not change anything (it only takes more memory because every part is stored as an separate object, but it won't affect the user that much) Commented Feb 10, 2013 at 21:36
  • A <thead> element has permitted content of Zero or more <tr> elements. You should wrap your <th> tags together in a <tr>. Commented Feb 10, 2013 at 22:10

1 Answer 1

3
  1. you don't call drawTable()
  2. remember to call it after <div id="numbersTable"></div>
Sign up to request clarification or add additional context in comments.

5 Comments

That's what I'm confused about. Where should I call the function drawTable?
1. window.onload = drawTable; 2. <script>drawTable();</script> just before the </body> tag - these are simplest options, choose which you want (I suggest the second)
I got another quick question, if I was to style the table with external CSS sheet would I add elements inside the function or does it need to go in the body?
I don't understand what do you mean, you just put CSS rules into stylesheet and they will be appened right after call drawTable()
I have external CSS style sheet that that I link to. If I wanted to apply the styling from external CSS sheet to my table would I just do it inside my function where I started the table? Like tableDiv.innerHTML = "<table class="styledtable">"

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.