0

I'm tying to read and output a text file. The Chrome console complains:

caught TypeError: Cannot read property '0' of undefined FinanceDashBoard.html:22"

Not sure what I am doing wrong ?

The code is as follows:

<html>
    <head>
       <title>Read File (via User Input selection)</title>
    </head>
<body>
    <main>
      <label>Load a text database file: <input type="file" id="txtfile" ></label>
    </main>

  <script type="text/javascript">

  var dbFileElm = document.getElementById('txtfile');

  dbFileElm.onchange =  function() {
    var filePath = dbFileElm.files[0];
    var reader = new FileReader();
    var output = ""; //placeholder for text output
    reader.onload = function (e) {
      output = e.target.result;
      displayContents(output);
      }
    reader.readAsText(filePath.files[0]);
  }   

  // Ignore code below it doesn't work yet.
  function displayContents(txt) {
    var el = document.getElementById('main'); 
    el.innerHTML = txt; //display output in DOM
  }

  </script>
 </body>
</html>
1
  • Which line is the error happening on? Commented Jul 29, 2014 at 7:42

3 Answers 3

7

Two mistakes.

1) Change this line:

reader.readAsText(filePath.files[0]);

to this:

reader.readAsText(filePath);

Because filePath is already: dbFileElm.files[0];

2) The main tag has no ID, so getting element by ID main will not work. Just edit it to:

<main id="main">
Sign up to request clarification or add additional context in comments.

7 Comments

Or #2 could use getElementsByTagName.
document.getElementsByTagName("main")[0]
is main even a valid tag in HTML5?
main is valid in HTML5 according to the current W3C HTML5 LC. But this is not relevant here; its being or not being valid does not affect what browsers do.
Cheers Valentin - I completely missed that.
|
3

You have no elements that have id="main"

Try something like...

<main id="main"> ...

Or if you're trying to populate your text box...

var el = document.getElementById('txtfile');

1 Comment

That doesn't seem related to the error he's getting. He never tries to read property 0 of el.
0

this post has answer to question

HTML input file selection event not firing upon selecting the same file

and if you set your input value to null, is working for me

dbFileElm.onChange =  function() {
    this.value = null;
    var filePath = dbFileElm.files[0];
    var reader = new FileReader();
    var output = ""; //placeholder for text output
    reader.onload = function (e) {
      output = e.target.result;
      displayContents(output);
      }
    reader.readAsText(filePath.files[0]);
  }   

Comments

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.