I am working on a html project in which the user uploads a txt file whose content is further processed and the result shown. The upload and processing step works fine but somehow the result is never shown. The (for me) confusing part is that if I add an alert() between processing and result presentation, the result is then displayed correctly.
Is this a known issue that I am missing?
In the code example bellow, if you remove the commentary on the alert(), the result is displayed correctly in the "demo" paragraph. But without it, nothing is shown.
I'd be grateful for either an explanation of my mistake or an alternative solution.
Thank you very much!
function myFunction() {
var x = document.getElementById("file");
var textFromFileLoaded = "";
if (x.value != "") { // text upload
var file = x.files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
textFromFileLoaded = fileLoadedEvent.target.result;
}
fileReader.readAsText(file, "UTF-8");
}
//alert("somth"); //HERE
document.getElementById("demo").innerHTML = textFromFileLoaded;
return true;
}
Select a file to upload:
<input type="file" id="file" size="50" accept="image/*">
<button onclick="myFunction()">button</button>
<p id="demo"></p>