Reza Shoja
Reza Shoja

Reputation: 927

modify the behavior of input element with tag 'multiple'

I have a form in which I want the user to upload multiple photos. normally when I choose multiple files at once, it works fine. but the problem is that if the user wants to add images one by one, after each addition, the previous file gets deleted(As the length of files after each addition is 1). how do I fix this? thanks

$("#files").change(function(){
  console.log("the length of files: ", $("#files")[0].files.length); 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <input type="file" name="" id="files" multiple>
</form>

Upvotes: 0

Views: 64

Answers (2)

Zlatko
Zlatko

Reputation: 19578

The problem you're having is that the the <input> tag is acting "atomically" here. Whatever you select, you select. If you wanna be able to add other elements later, you'd have to either use a plugin (like suggested), or handle this yourself.

let allFiles = [];
$('#files').change(function() {
  this.allFiles = this.allFiles.concat($("#files")[0].files);
  showFileNames();
});

Note how I've said that the files are "concatenated" to the allFiles variable.

Also, the showFileNames function could render all files, or e.g. just file names into a table or a list or something. And by each file you might also have a "x", to remove it.

Now when you're submitting a form later, you use allFiles instead of that input directly, e.g. by building a FormData yourself.

Upvotes: 1

Nick Parsons
Nick Parsons

Reputation: 50854

You can keep an array of files, and add each file to this array. This way you will have a running total of all the files added. The issue with your current approach is that your files are getting overwritten, upon each upload, thus, saving them to an array is one way around this.

See working example below:

let uploaded_files = [];
$("#files").change(function(){
  let currentFiles = $("#files")[0].files;
  uploaded_files = [...uploaded_files, ...currentFiles];
  console.log(uploaded_files.length); 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <input type="file" name="" id="files" multiple>
</form>

Upvotes: 1

Related Questions