Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit the maximum files chosen when using multiple file input

Tags:

html

file

When using <input type="file" multiple> it's possible for the user to choose multiple files.

How does ones sets a limit for how many files can be chosen, for instance two?

like image 584
rjmcb Avatar asked Apr 11 '12 11:04

rjmcb


People also ask

How do I limit maximum items in multiple inputs?

For limiting maximum items on multiple inputs, use JavaScript. Through this, limit the number of files to be uploaded. For example, let's say only 2 files to be uploaded at once. You can try to run the following code to learn how to use multiple attributes in HTML.

Which input property allows you to select many files at once?

The multiple attribute is a boolean attribute. When present, it specifies that the user is allowed to enter more than one value in the <input> element. Note: The multiple attribute works with the following input types: email, and file.


2 Answers

You could run some jQuery client-side validation to check:

$(function(){     $("input[type='submit']").click(function(){         var $fileUpload = $("input[type='file']");         if (parseInt($fileUpload.get(0).files.length)>2){          alert("You can only upload a maximum of 2 files");         }     });     });​ 

http://jsfiddle.net/Curt/u4NuH/

But remember to check on the server side too as client-side validation can be bypassed quite easily.

like image 123
Curtis Avatar answered Sep 30 '22 11:09

Curtis


On change of the input track how many files are selected:

$("#image").on("change", function() {      if ($("#image")[0].files.length > 2) {          alert("You can select only 2 images");      } else {          $("#imageUploadForm").submit();      }  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>  <strong>On change of the input track how many files are selected:</strong>  <input name="image[]" id="image" type="file"  multiple="multiple" accept="image/jpg, image/jpeg" >
like image 27
Kristian Antov Avatar answered Sep 30 '22 13:09

Kristian Antov