Reputation: 759
I'm attempting to create a webpage to visualize a family tree using JSON. I'm using the uploadJSON()
function to store the JSON data from a file in to the global variable tree
, which seems to work until I try to access tree
in another function. When I do console.log(tree);
in addToDropDown()
it shows up in the console as undefined. I've tried setting tree
to a default value of "Testing"
when it's initialized, which does not get overwritten when I call uploadJSON()
.
let tree;
let dropDown;
window.onload = function() {
// Upload JSON File
document.getElementById( 'upload-button' ).onclick = function() { uploadJSON(); };
// Get Dropdown
dropDown = document.getElementById( 'family-memeber-select' );
}
function uploadJSON() {
let files = document.getElementById( 'upload-file' ).files;
if( files.length <= 0 ) {
return false;
}
let fr = new FileReader();
fr.onload = function( e ) {
console.log( e );
let result = JSON.parse( e.target.result );
tree = result;
console.log(tree); // This outputs the tree object from the JSON file as expected
}
fr.readAsText( files.item(0) );
addToDropdown();
}
function addToDropdown() {
// Add all family members to a dropdown list
console.log( tree );
}
Upvotes: 1
Views: 31
Reputation: 558
fr.onload
sets an event listener, then addToDropdown()
function is being called so when it's called, fr.onload
is not called yet, I think the best solution would be calling addToDropdown()
function in fr.onload
event, so the function will be called when the event is fired
Upvotes: 1