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?
            Asked
            
        
        
            Active
            
        
            Viewed 72 times
        
    2 Answers
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
 
- 
                    I think, we don't actually need to parse the length in integer..! As it will always return an integer value..! – Rohit Sharma Jul 29 '19 at 12:40
 - 
                    @RohitSharma True, bit tired, thanks for pointing it out. – Carsten Løvbo Andersen Jul 29 '19 at 12:42
 
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