So i have a table that's generated with JavaScript from a JSON. Inside the table there's a File Upload button that I need to swap images (all the images are in the same folder so I only need the name of the file) The process of generation looks like this
ImageClick = document.createElement('input');
ImageClick.type = "file";
ImageClick.id = "subida"
ImageClick.onChange = handleFiles();
cell.appendChild(ImageClick);
handleFiles function
function handleFiles() {
const fileList = this.files;
console.log(fileList[])
}
So when the table is generated, the handleFiles function is triggered right away, before even selecting a File, so I get an
Uncaught TypeError: fileList is undefined
as soon as the page loads. If I try to load the file upload element with
filesElement = document.getElementById('subida')
and I try to console log the filesElement I get
Uncaught TypeError: filesElement is null.
I've been looking through the internet and I can't find an answer. Also I can't use jQuery
CodePudding user response:
This will work also:
ImageClick.addEventListener("change", function(e) {
const fileList = e.target.files;
console.log(fileList);
});
CodePudding user response:
Try it like this? You can take the event as an argument in your handler function.
<!DOCTYPE html>
<html>
<body>
<p id="hello">Modify input field to fire the onchange event.</p>
<script>
var element = document.getElementById("hello");
ImageClick = document.createElement('input');
ImageClick.type = "file";
ImageClick.id = "subida"
ImageClick.addEventListener("change", handleFiles);
element.appendChild(ImageClick);
function handleFiles(val) {
const fileList = val.target.files;
console.log(fileList)
}
</script>
</body>
</html>