1

I am writing a utility that will (should) allow the user to attach a text document ('test.txt') and store the content of that file into the global variable output. What I don't understand (I've gotta be missing something here) is that within the below code (alert(output + " | " + test);) returns output as undefined but test as "Hello"

It's like the fileReader disposes of everything once it finishes so output gets set back to undefined. However, by setting the innerText of a div element (output), it prints the data to the page just fine if everything is within the fileReader.onload function. If it's outside of it, it's undefined.

So, in short, why is output undefined?

JavaScript:

var output;
var test;
function loadContent() {
    var fileReader = new FileReader();
    var xmlDoc;
    test = "Hello";
    fileReader.readAsText(document.getElementById("slnFile").files[0]);
    fileReader.onload = function (event) {
        output = event.target.result.toString();
        document.getElementById("output").innerText = output.toString();
    };
    alert(output + " | " + test);
}

HTML

<!DOCTYPE Html />
<html>
    <head>
        <title></title>
        <link rel="stylesheet" href="theCSS.css" />
    </head>
    <body>

        <p>Solution: <input id="slnFile" type="file" onchange="loadContent();"/></p>

        <div id="output"></div>

        <script type="text/javascript" src="jQuery_v1.10.2.js"></script>
        <script type="text/javascript" src="jquery-ui.min.js"></script>
        <script type="text/javascript" src="theJS.js"></script>

    </body>
</html>
mwilson
  • 12,295
  • 7
  • 55
  • 95

0 Answers0