How to print the file name

I am trying to print the name of the downloaded files, but for some reason it only prints the first file.

The script allows you to load unlimited files and why an array of arrays.

$(document).on('submit', 'form', function(e) {
    e.preventDefault(); 

    var $form = $(this);
    var act = 'add';

    var files = $form.find('.file-field').prop('files');
    var names = "";

    $.each(files,function(i, file){
        name = file.name;
        alert(name);
    });

});

HTML

<form class="form-horizontal" action='#' method="post"  enctype="multipart/form-data">
    <input type='file' name='file[]' class=' form-control file-field multi' maxlength='2' accept="image/jpg,image/png,image/jpeg,image/gif"  id="uploadFile0"/>
    <button class="btn btn-primary submit" >SEND</button>
</form> 
+4
source share
1 answer

prop() returns the property value for the first element in the set of matched elements or sets one or more properties for each matched element.

Taken from http://api.jquery.com/prop/

So use each()iteration over jQuery objects and the rest as such

$(document).on('submit', 'form', function(e) {
  e.preventDefault();

  var $form = $(this);
  var act = 'add';

  $form.find('.file-field').each(function() {
    var files = $(this).prop('files');
    var names = "";
    $.each(files, function(i, file) {
      var name = file.name;
      alert(name);
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form class="form-horizontal" action='#' method="post" enctype="multipart/form-data">
  <input type='file' name='file[]' class=' form-control file-field multi' maxlength='2' accept="image/jpg,image/png,image/jpeg,image/gif" id="uploadFile0" />
<input type='file' name='file[]' class=' form-control file-field multi' maxlength='2' accept="image/jpg,image/png,image/jpeg,image/gif" id="uploadFile0" />
  <button class="btn btn-primary submit">SEND</button>
</form>
Run code

Update: You can simplify your code.

$(document).on('submit', 'form', function(e) {
  e.preventDefault();
  var $form = $(this);
  $form.find('.file-field').each(function() {
    var name = this.files[0].name;
    alert(name);
    console.log(name);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form class="form-horizontal" action='#' method="post" enctype="multipart/form-data">
  <input type='file' name='file[]' class=' form-control file-field multi' maxlength='2' accept="image/jpg,image/png,image/jpeg,image/gif" id="uploadFile0" />
<input type='file' name='file[]' class=' form-control file-field multi' maxlength='2' accept="image/jpg,image/png,image/jpeg,image/gif" id="uploadFile0" />
  <button class="btn btn-primary submit">SEND</button>
</form>
Run code
+1
source

Source: https://habr.com/ru/post/1607519/


All Articles