I've found many JavaScript tutorials on reading plain text from local files and on displaying that text onto a webpage element, but I cannot seem to find how to SAVE the data into an array that I can access from other parts of my script.
If I try to assign the text from the file to a global variable INSIDE the FileReader.onload()
method, I can't access it OUTSIDE the method. Any advice?
The code below is for a school timetable project that I'm doing with my students that uses local files of courses, students, and teachers. I have a file input element defined as:
<input type="file" id="courseFile" onchange="School.addCourses(event);">
Then my School constructor includes the following arrays and methods:
function School (name) {
this.courses = [];
this.students = [];
this.teachers = [];
this.addCourses = function (event) {
var fileInput = event.target;
var r = new FileReader();
r.readAsText(fileInput.files[0]);
r.onload = function (e) {
var text = r.result;
var array = text.split("\n");
document.getElementById("courseList").innerHTML = text;
this.courses = array;
}
}
}
The text is loaded into text
and then split into array
and will even display on the page in the courseList
element, but it does not copy the data into this.courses
.