Kob_24 Kob_24 - 7 months ago 11
Javascript Question

Append element to input control

I have Two input buttons that allow user to upload files

<input type="file" id="fileUpload" name="files" multiple><br/>
<div id="selectedFiles"></div>


into the selectedFiles div i append a list of file names:

$('input:file').on('change', function() {
//$('.file').bind('change', function() { // is duprecated
var files = this.files;
var listOfFiles = [];

for(var i=0; i < files.length; i++) {
//var filename = files[i].name + "<br />";
//$("#selectedFiles").append(filename);
listOfFiles.push(files[i].name);
}

$('#selectedFiles').append(listOfFiles.join("<br />"));
});


What i need to do is to append the list of files under each button. any idea on how to do so?

Answer

Replace $( '#selectedFiles' ).append with $(this).after. Probably should wrap all the files inside a list for cleanliness. Here's a better way:

$(this).after('<ul><li>' + listOfFiles.join('<li>') + '</ul>')

Here's the final code (I cleaned it up a little):

$(function() {
  $( '.upload_files_input' ).on('change', function() {
    var file_names = Array.prototype.slice.call(this.files).map(function(file) {
      return file.name;
    });
    $(this).after('<ul><li>' + file_names.join('<li>') + '</ul>');
  });
});
Comments