Open several times multiple file input without losing earlier selected files

Vince Varga picture Vince Varga · Apr 1, 2015 · Viewed 7.3k times · Source

I have a multiple file input. I want my customers to choose multiple files when they click on 'Choose files' (I think it is done) and if they forget to select some files, I want my code to enable selecting new files (done) AND add that data to the data that they have selected before (couldn't solve it).

How can I append the new files to the list?

Just to give you the context: my goal after this is to send each file with AJAX to my PHP server.

Any help, hint is appreciated!

Answer

tkay picture tkay · Apr 1, 2015

I believe the same element cant be used for the mentioned use. Here is a workaround. On a file input click append another file input and hide the current one.

 

  

  $("#seebtn").click(function(e) {
      $('#displayFileNames').html('');
      var domArray = document.getElementsByClassName('file-input');
      for (var i = 0; i < domArray.length; i++) {
         var files =  domArray[i].files;
       
        for (var j = 0; j < files.length; j++){
        $('#displayFileNames').append(files[j].name + '</br>');
      }
      };
      

      // Send data with AJAX.
    });
 function myFunction(obj) {
  $(obj).hide();
  $("#upload-form").append("<input class='file-input' type='file' onclick='myFunction(this)' name='file[]' multiple='multiple' />");
    }
 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button value="See what's in there" id="seebtn">see</button>
<form id='upload-form' action='' method='post' enctype='multipart/form-data'>

    <input id='myFileInput' class='file-input' type='file' name='file[]' onclick="myFunction(this)" multiple='multiple' />
    
</form>
<div id="displayFileNames"></div>