I am seeking a JavaScript code that can verify the size of an input file before uploading whenever the user changes the input value (i.e. whenever a file is selected for upload).
Here is what I have come up with so far:
var file = document.getElementById("myFile");
file.addEventListener('change', function() {
if (this.files[0].size > 2*1024*1024) {
alert('Max file size is 2 MB');
file.removeAttribute('value');
file.parentNode.replaceChild(file.cloneNode(true),file);
}
}
);
The accompanying HTML code is as follows:
<form action="?" method="post">
<input type="file" id="myFile" name="myFile" />
<input type="submit" value="upload" />
</form>
If I keep the JavaScript code as is, it does not function properly. However, when I modify it like this
window.onload = function() {
// Code remains the same
}
it works, but only for the first file that the user selects.
How can I adjust it to ensure it functions every time a user selects a file? (if possible without jQuery)