Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JS – Check *all* selected files on dragenter, error if any do not meet requirement

I have a drag and drop image "uploader" (it does not upload, only converts to base64 and displays thumbnails). Currently if you drag one file into the dropzone, if it is not a .jpg/.jpeg it will show error (this is correct functionality), but if you drag multiple files into the dropzone, it does not show the error if at least 1 file is a jpg, even if the other file(s) do not meet jpg requirement, which is not what should happen (ex: you select .jpg and .zip, this will not trigger error, but it should). I need to show the error always unless all selected files are .jpg. Can anyone assist?

Here is the relevant dragenter code (same code for dragover)

container.addEventListener(
"dragenter",
(e) => {
e.preventDefault();
e.stopPropagation();
const img = Array.from(e.dataTransfer.items).find(e => e.type.match('image/jpeg'))
if (img){
   container.classList.add("active");
}else{
  error.innerHTML = "HTML removed from snippet for readability";
  error.classList.remove("hideit");}
},
false
);

https://jsfiddle.net/x2fyrcLb/2/

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try changing "find" to "every" (search MDN documentation for "Array.prototype.every"):

const img = Array.from(e.dataTransfer.items).every(e => e.type.match('image/jpeg'))

There’s another array method, some, for checking "if at least one".

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading