0

I have a input File upload field in my HTMl, i want to get only 5 images, selecting more than 5 image should display warning or alert anything. How to achieve this with javascript or jquery?

Nandhini Kajol
  • 75
  • 1
  • 4
  • 14

2 Answers2

0

You could try something like the following.

$("input[type='file']").change(function() {
  var $fileUpload = $("input[type='file']");
  if ($fileUpload.get(0).files.length > 5) {
    alert("You can only upload a maximum of 5 files");
    $(this).val("")
  }
});

Demo

$("input[type='file']").change(function() {
  var $fileUpload = $("input[type='file']");
  if ($fileUpload.get(0).files.length > 5) {
    alert("You can only upload a maximum of 5 files");
    $(this).val("")
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" multiple />
Carsten Løvbo Andersen
  • 26,637
  • 10
  • 47
  • 77
0

You can check the size of the input, and clear the files if there are too many:

const fileUploadLimit = 2;

const resetFileInput = input => {
    input.type = '';
    input.type = 'file';
}

document.querySelector('input').onchange = (e) => {
  const { files } = e.target;
  if (files.length > fileUploadLimit) {
    console.log(`cannot upload more than ${fileUploadLimit} files`);
    resetFileInput(e.target);
  }
}
<input type="file" name="img" multiple>
OliverRadini
  • 6,238
  • 1
  • 21
  • 46