Reputation: 348
After adapting the How FileReader.readAsText in HTML5 File API works? code to my purposes. It gives me an error.
Uncaught TypeError: Cannot read property 'addEventListener' of null
var button = document.querySelector('#fileInput + button');
var input = document.getElementById('#fileInput');
var text = null;
input.addEventListener("change", addDoc);
button.addEventListener("click", handleText);
function addDoc(event) {
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(e) {
text = reader.result;
button.removeAttribute("disabled");
};
reader.onerror = function(err) {
console.log(err, err.loaded, err.loaded === 0, file);
button.removeAttribute("diabled");
};
reader.readAsText(event.target.files[0]);
console.log(reader.readAsText(event.target.files[0]));
}
function handleText() {
addtoPreviousOutput();
changeOutputParagraph(text);
button.setAttribute("disabled", "disabled");
}
function changeOutputParagraph(newText) {
var element = document.getElementById("output");
element.innerHTML = newText;
}
function addtoPreviousOutput() {
var previousOutput = document.getElementById("output").innerHTML;
var previousOutput_sOutput = document.getElementById("previousOutput").innerHTML + "<br />";
console.log(previousOutput);
console.log(previousOutput_sOutput);
document.getElementById("previousOutput").innerHTML = previousOutput_sOutput + previousOutput;
}
<input type="file" id="fileInput" accept="text/*"/>
<button type="button">Add Document</button>
<p id="output"></p>
What is my error caused by and how can I fix it? Thanks, DS_Secret.
Upvotes: 0
Views: 704
Reputation: 287815
When the code
var input = document.getElementById('#fileInput');
input.addEventListener("change", addDoc);
fails with the message Uncaught TypeError: Cannot read property 'addEventListener' of null
, it follows that document.getElementById('#fileInput')
returns null.
This, in turn, means that there was no element with the ID '#fileInput'
at the time the code ran. This is true, you only have a similarly id-ed element with id="fileInput"
, without a leading #
character. So set input like
var input = document.getElementById('fileInput');
or
var input = document.querySelector('#fileInput');
In addition, make sure that the JavaScript code does not run too early. Normally, everything that depends on the DOM should only be called once the DOMContentLoaded
event has fired, especially if your script tags located are in the document head. Otherwise, when the JavaScript runs, the DOM may not include the desired elements yet.
Upvotes: 2
Reputation: 1704
I thing you are using the method document.getElementById wrong.
Try using
var input = document.getElementById('fileInput');
Instead of
var input = document.getElementById('#fileInput');
Upvotes: 1