1

I am having this issue where the table is not being displayed with my Javascript. It is suppose to work to where once the user enters the 10 numbers in the window.prompt the numbers would be put into an array and displayed into a table.

Here is the code:

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

var number = -99;
var array1 = new Array(10);

number = window.prompt("Enter 1 to continue \n Enter -99 to exit");
if(number == -99 || number == ""){
    exit();
}else
    array1 = window.prompt("Please enter 10 numbers to be stored into an array");

    function outputArray(heading, theArray, output){
    var content = "<h2>" + heading + "</h2><table><thead><th>Index</th><th>Value</th></thead><tbody>";
    var length = theArray.length;
    for(var i=0; i<length;++i){
    content += "<tr><td>" + i + "</td><td>" + theArray[i] + "</td></tr>";
    }
    content += "</tbody></table>";
    output.innerHTML = content;
    }

    outputArray("Your Array is:", array1, document.getElementById("output"));
</script>
</head>
<body>
<div id="output"></div>
</body>
</html>

1 Answer 1

1

You should wrap your script in a onload handler:

var onLoadHandler = function() {
    var number = -99;
    var array1 = new Array(10);

    number = window.prompt("Enter 1 to continue \n Enter -99 to exit");
    if(number == -99 || number == ""){
        exit();
    }else
        array1 = window.prompt("Please enter 10 numbers to be stored into an array");

        function outputArray(heading, theArray, output){
            var content = "<h2>" + heading + "</h2><table><thead><th>Index</th><th>Value</th></thead><tbody>";
            var length = theArray.length;
            for(var i=0; i<length;++i){
            content += "<tr><td>" + i + "</td><td>" + theArray[i] + "</td></tr>";
            }
            content += "</tbody></table>";
            output.innerHTML = content;
        }

        outputArray("Your Array is:", array1, document.getElementById("output"));
}
if (window.addEventListener) {
    window.addEventListener('load', onLoadHandler, false);
} else if (window.attachEvent) {
    window.attachEvent('onload', onLoadHandler );
}

I.e. you are trying to manipulate a DOM element, which may be still not there.

Sign up to request clarification or add additional context in comments.

1 Comment

That works perfect. I need to do some research on these window.addEventListener and attachevent. Any recommendations for a good tutorial? And Thank you very much.

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.