0

I have a file reader that works on jfiddle but wont work in any browser. Im using all the latest browsers,. It will let me select the file, but nothing happens afterwards. Im very new to javascript.

javacript

<script type="text/javascript">
function readFile(file) {
    var reader = new FileReader();
    reader.onload = readSuccess;

    function readSuccess(evt) {
        var field = document.getElementById('main');
        field.innerHTML = evt.target.result;
    };
    reader.readAsText(file);
}

document.getElementById('selectedFile').onchange = function(e) {
    readFile(e.srcElement.files[0]);
};
</script>

html

<input type="file" id="selectedFile" />
<div id="main"></div>

jfiddle

http://jsfiddle.net/fstreamz/ngXBV/1/
2
  • Hello! Could you provide a link to the jsFiddle in which this is working? jsFiddle uses your browser's engine to run script (there's nothing special about its execution model), so there must be something that jsFiddle is doing that your browser code is not doing. Commented Apr 21, 2016 at 14:27
  • 1
    jsfiddle wraps javascript within onload event, which can be viewed by inspecting source at jsfiddle. Use window.onload = function() {//do stuff} to call function after page resources; that is DOM elements. have fully loaded into document Commented Apr 21, 2016 at 14:36

1 Answer 1

1

Use window.onload or window.addEventListener("load")

<script type="text/javascript">
  window.onload = function() {
  function readFile(file) {
    var reader = new FileReader();
    reader.onload = readSuccess;

    function readSuccess(evt) {
      var field = document.getElementById("main");
      field.innerHTML = evt.target.result;
    };
    reader.readAsText(file);
  }

  document.getElementById("selectedFile").onchange = function(e) {
    readFile(e.srcElement.files[0]);
  };
}
</script>
Here is the html

<input type="file" id="selectedFile" accept="text/plain" />
<div id="main"></div>

Sign up to request clarification or add additional context in comments.

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.