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>
Valentin Mercier
  • 5,256
  • 3
  • 26
  • 50
Mihira
  • 21
  • 4

3 Answers3

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">
Valentin Mercier
  • 5,256
  • 3
  • 26
  • 50
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');
Jonathon
  • 15,873
  • 11
  • 73
  • 92
  • That doesn't seem related to the error he's getting. He never tries to read property `0` of `el`. – Barmar Jul 29 '14 at 07:40
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]);
  }   
Community
  • 1
  • 1
pappu_kutty
  • 2,378
  • 8
  • 49
  • 93