Reputation: 113
I'm trying to display one or multiple file names before a user submits the files, but as of now I can only display one file name rather than multiple file names if a user decides to select multiple files.
Jquery
$(function() {
$('input:file').change(function(){
var fileName = $(this).val();
$('.filenames').html('<div class="name">' + fileName + '</div>');
});
});
Upvotes: 1
Views: 3755
Reputation: 24001
You can use for
loop with this.files.length
$(function() {
$('input:file').change(function(){
for(var i = 0 ; i < this.files.length ; i++){
var fileName = this.files[i].name;
$('.filenames').append('<div class="name">' + fileName + '</div>');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" name="files[]" multiple />
<div class="filenames"></div>
OR $.each
with this.files
Updated: 08/02/2020
$(function() {
$('input:file').on('change' , function(){
$.each(this.files , (i , v) => {
var filename = v.name;
$('.filenames').append('<div class="name">' + filename + '</div>');
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" name="files[]" multiple />
<div class="filenames"></div>
Upvotes: 5
Reputation: 2449
Replace below
$('.filenames').html('<div class="name">' + fileName + '</div>');
to
$('.filenames').append('<div class="name">' + fileName + '</div>');
html
replaces the existing element with new one. Where as append
merges the current content with existing one.
Upvotes: 4