Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript – Load a file twice in a row

Good day,

I have the following code to load a ".TXT" file into a web page

function load(event) {
  let fr = new FileReader();
  fr.onload = function() {
    let load0 = JSON.parse(fr.result);
    console.log(load0);
    console.log("Ready!");
  };
  fr.readAsText(event.target.files[0]);
}

function loadInput(event) {
  document.getElementById("loadInputButton").click();
}
<html>

<body>
  <input type="button" onclick="loadInput(event)" />
  <input id="loadInputButton" type="file" accept="text" onchange="load(event)" />
</body>

</html>

It works fine but only once. After I once load the file it will not work anymore. I try to load the same file again but the function produces nothing.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

May I ask for your help solving it?

Thank you,
Eugene

>Solution :

Clear the value of the input after using it, so that the change event will fire when you select the same file.

function load(event) {
  let fr = new FileReader();
  fr.onload = function() {
    let load0 = JSON.parse(fr.result);
    console.log(load0);
    console.log("Ready!");
    event.target.value = '';
  };
  fr.readAsText(event.target.files[0])
}

function loadInput(event) {
  document.getElementById("loadInputButton").click();
}
<html>

<body>
  <input type="button" onclick="loadInput(event)" />
  <input id="loadInputButton" type="file" accept="text" onchange="load(event)" />
</body>

</html>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading