0

I am quite new B in javascript programming and I read the professional javascript for developers book 3rd edition. in addition I have tried many options from the site How can you read a file line by line in JavaScript? or this: How can you read a file line by line in JavaScript?.

With the second option I have a problem with understanding what he meant by "file field is rendered" when saying "Remember to put your javascript code after the file field is rendered". Nevertheless I tried it and it didn't work.

Now from my understanding of how file reading works the following code should work but it doesn't, and I don't know why. I hope I am not very boring.

<p id="output">
</p>
<form id="form1" action="">
  <input type="file" id="input">
  <input type="button" id="readFil" value="read" onsubmit="readFile()">
</form>
<script>
  function readFile() {
    var selected_file = document.getElementById('input').files[0];
    reader = new FileReader();
    reader.readAsText(selected_file);
    reader.onload = function() {
      document.getElementById("output").innerHTML = reader.result;
    };
  }
</script>
Community
  • 1
  • 1
zeroday
  • 153
  • 2
  • 14

1 Answers1

1

Because input elements have no submit event. form elements do. If you want your code called when the button is pressed, use the click event.

<input type="button" id="readFil" value="read" onclick="readFile()">
<!-- Change is here -----------------------------^^^^^           -->
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875