To limit the maximum files chosen when using multiple file inputs with JavaScript, we check the length of e.files
.
For instance, we write
<input multiple type="file" onchange="trySubmitFile(event)" />
to add a file input.
We set its onchange
attribute to call trySubmitFile
with the event
object.
Then we write
function trySubmitFile(e) {
const files = e.target.files;
if (files.length > 5) {
alert("You are only allowed to upload a maximum of 2 files at a time");
}
//...
}
to define the trySubmitFile
function.
We check if the number of selected files is bigger than 5 with files.length > 5
.
We get the select files with e.target.files
.