Reputation: 606
New to JS, so hopefully this is an easy fix. I'm trying to change the innerHTML from "File Upload" to the name of the file they chose. This works, but then when I click the "Upload" button, it get this error:
Uncaught TypeError: Cannot read property 'value' of null
at HTMLInputElement.upload
From my understanding, it's saying no value exists for the html element with id="upload"
which is confusing because the HTML element with that ID is a button.
My HTML:
<form id="uploadForm" method="post" enctype="multipart/form-data">
<label class="custom-file-upload" id="fileUploadLabel">
<input type="file" name="file" id="dataUpload"/>File Upload
</label>
<input type="button" value="Upload" id="upload"/>
</form>
My JS:
dom.byId('dataUpload').onchange = uploadOnChange;
function uploadOnChange() {
var filename = this.value;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
}
dom.byId('fileUploadLabel').innerHTML = filename;
}
on(dom.byId("upload"), "click", upload);
function upload(){
//Disable the upload button after click
functionalBtn("disable");
//Check that form was fully filled out
var dataUpload = dom.byId("dataUpload").value;
if (dataUpload == ""){
alert("Please choose a zip file to upload.");
functionalBtn("enable");
return false;
}
else if (!dataUpload.endsWith(".zip")){
alert("The input file must be a zip file.");
functionalBtn("enable");
}
else{
//upload the zip file and get back the itemID (via uploadSucceeded)
var upload = esri.request({
url: "https://xxxxxx",
form: dojo.byId("uploadForm"),
content: {f: 'json'},
handleAs: 'json',
}).then(uploadSucceeded, uploadFailed);
}
}
Am I somehow changing the value of id="dataUpload"
when I change the label text? In my upload()
function that is where I check the value of dataUpload
after clicking the Upload button.
When I comment out dom.byId('fileUploadLabel').innerHTML = filename;
everything works again (except the file name doesn't show in the file upload box which isn't what I want).
Upvotes: 1
Views: 1708
Reputation: 16609
The problem is is that the innerHTML of the FileUploadLabel isn't File Upload
, it is <input type="file" id="dataUpload">File Upload
. After setting the innerHTML of the label, this becomes MyFile.txt
.
In other words, the element dataUpload
no longer exists!
So in upload() when you call dom.byId("dataUpload").value
, you are getting the value of a non-existent element. Also this will obviously cause issues when you come to actually do the upload.
The at HTMLInputElement.upload
bit isn't saying that upload is missing, it is part of the stack trace, saying which bit of code the error happened in.
You probably want to put the label text (File Upload) into a separate <span>
and set the innerHTML of that instead.
Upvotes: 1