Issue
My apologies for the stupid question, but I am trying to change the name of a button upon uploading a file. My code to change it is this, via TypeScript:
const i = (document.querySelector('label') as any).innerText = filename;
The code above, inside the fileName method, changes the "Upload Project File" text into the name of whatever file that is uploaded.
<div class="row">
<div class="clg6 cmd8 csm10 cxs12" v-if="this.projectFile">
<button
class="button primary outline medium upload">
<label>
<input
type="file"
name="projectFile"
id="fileName"
accept=".xls, .xlsx, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
v-on:change="validateFileType(); hashContentMD5(); fileName; getPresignedURL()"/>
<i class="fas fa-cloud-upload"></i>
Upload Project File
</label>
</button>
</div>
</div>
And it works. However, upon change, it brings up errors in my other methods when they're called, such as this:
const file = (document.getElementById('fileName')as any).files[0]
The error that shows up is
Uncaught (in promise) TypeError: Cannot read properties of null (reading 'files')
Removing the document.querySelector removes the error. This is the first time that I've encountered this. How can I fix it?
Solution
Problems:
You put your input inside the label tag. I learned this is okay.
- Why using a
buttonoutside the wholelabelandinputtags? I don't understand what your intention was with that. - You replace the inside of the
labeltag by a text node (containing the file name). Through your replacement you delete yourinputfield out of the DOM. SeequerySelectorline in your code. - After having replaced the input field, there is no
fileNameon the page anymore, so itgetElementByIdresults innull.
Solution:
- (optionally) I'd delete the
buttontag and only keep the inside of it. - Don't operate on that
labeland don't try to overwrite the value of a fileinputfield - By not removing the
inputfield anymore, you can access it and read out the file name
See my example here: https://stackblitz.com/edit/js-fdxxnf
Answered By - Janos Vinceller
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.