1

I'm trying to read an input type="file" tag into a javascript string. I know this should be simple but I simply cannot get my code to work. The file is plain .html. Here's what I have

    <h3>Select location of html file.</h3>
    <form onSubmit="submitButtonPressed()">
    <input type="file" id="classList" />
    <input type="submit" />
    </form>

    <script>
        var reader = new FileReader();
        var htmlFile = document.getElementById("classList").files[0];   //read the file selected with the <input> tag
        reader.readAsText(htmlFile);            
        var htmlText = reader.result;  //and create a string with the contents

        function submitButtonPressed() {
             var lengthOfText = htmlText.length;
             alert("It is " + lengthOfText + " characters long");
        }
    </script>

I'm just trying to create a string that contains the contents of the .html file selected by the input tag. I can't figure out why htmlText doesn't contain the contents of the .html file, could someone explain what I'm doing wrong?

jamzsabb
  • 1,125
  • 2
  • 18
  • 40

1 Answers1

0

this is the right answer for you :

HTML5 File API: How to see the result of readAsText()

reader.onload = function(e) {
    // e.target.result should contain the text
};
reader.readAsText(file);

so i guess you will have to check on pressing the button if the file was loaded or not , maybe it is still in progress , or encountered an error

Community
  • 1
  • 1
ProllyGeek
  • 15,517
  • 9
  • 53
  • 72
  • I don't understand what needs to go in the onload function though, what is the variable e supposed to be? Thanks for the reply though – jamzsabb Dec 19 '13 at 02:51
  • var htmlText = reader.result; //and create a string with the contents should be inside the on load function to ensure that data was loaded – ProllyGeek Dec 19 '13 at 04:16