Open several times multiple file input without losing earlier selected files

耗尽温柔 提交于 2019-12-21 17:11:59

问题


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.

$("#upload-form").submit(function(e) {
  $('#displayFileNames').html('');
  console.log('Currently in files.');
  var files = $('#myFileInput')[0].files;
  for (var i = 0; i < files.length; i++){
    $('#displayFileNames').append(files[i].name + '</br>');
    console.log(files[i].name);
  }

  // Send data with AJAX.
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id='upload-form' action='' method='post' enctype='multipart/form-data'>
    <input id='myFileInput' class='file-input' type='file' name='file[]' multiple='multiple' />
    <input type='submit' value="See what's in there" />
</form>
<div id="displayFileNames"></div>

Any help, hint is appreciated!


回答1:


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>
 


来源:https://stackoverflow.com/questions/29394126/open-several-times-multiple-file-input-without-losing-earlier-selected-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!