I fire input file via JS function like this:
JavaScript
x
4
1
function PujarFitxerGP() {
2
document.getElementById('FUFitxer').click();
3
};
4
This control have a onchange event to validate the file:
JavaScript
1
2
1
<input type="file" onchange="ValidateGP();return false;" ID="FUFitxer" style="display:none" />
2
Event is firing correctly but when I get the input file by Id not contains the file:
JavaScript
1
2
1
document.getElementById('FUFitxer').files[0].name; ------>UNDEFINED
2
If I do the same via input file (changing style=”display:none”) is working as expected.
How I can resolve this problem? What I did wrong?
Thanks!
Advertisement
Answer
You could use the onchange
event’s parameter to access the files object on change
JavaScript
1
8
1
function ValidateGP(e) {
2
const file = e.target.files[0];
3
console.log(file.name);
4
}
5
6
function PujarFitxerGP() {
7
document.getElementById('FUFitxer').click();
8
};
JavaScript
1
3
1
#FUFitxer {
2
display: none;
3
}
JavaScript
1
3
1
<input type="file" id="FUFitxer" onchange="ValidateGP(event)" />
2
3
<button onclick="PujarFitxerGP(event)">Click here!</button>