Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

362
Views
How to load file content to variable using FileReader

I would like to seek some help please regarding loading txt file content to variable using input element in javascript.

So i am working with java script file separate from html file, and when the user click on button to load the file from the html side as below:

<input type="file" id="selectedFile" accept=".txt" />

it fires the onchange event as below

document.getElementById('selectedFile').addEventListener('change', function () {
    var fr = new FileReader();
    fr.onload = function () {
        document.getElementById('display').textContent = fr.result;
        console.log(fr.result);
    }
    fr.readAsText(this.files[0]);
})

basically if i console log the fr.result as in the code up there, i can see the content with no issues, and also i have div element with id "display" and content gets updated no issues. however i am unable to get the fr.result to be stored into global variable and use it later on in my code. I tried the below code:

let test = "";
document.getElementById('selectedFile').addEventListener('change', function () {
    var fr = new FileReader();
    fr.onload = function () {
        document.getElementById('display').textContent = fr.result;
        test = fr.result;
    }
    fr.readAsText(this.files[0]);
})
console.log(test);

but the test variable in console comes out empty and runs even before i choose the file with input element. Any advices about what i missing here, and how i can get the file content using same method to be stored in variable? Thanks!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I tried it it works like this, it was maybe because your event listener function was an anonymous function, and you can't call this in anonymous function

<input type="file" id="selectedFile">
<p id="display"></p>
<script>
var fr = new FileReader();
let test;
document.getElementById('selectedFile').addEventListener('change', x);

    
function x() {
fr.onload = ()=>{
document.getElementById('display').innerText = fr.result;
console.log(fr.result);
test = fr.result;

}
fr.readAsText(this.files[0]);

}   


console.log(test);</script>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!