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?
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.
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.
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.
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" >
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With