1

Trying to display the file names from a file input element. I am able to console log when I am inside the onchange function but not the addeventlistener. In the code below the console.log('Inside change eventlistener'); will not execute. I can I both log being inside the event listener and get the file names in order to display them? Here is the codepen of the code. Thank you.

html:

<label>Attachments</label>
<div>
    <input type="file" class="form-control input-lg" name="attachments" id="attachments" multiple onchange="getFileData()">
</div>

js:

function getFileData() {
  console.log('Inside getFileData()...')
  var elem = document.getElementById('attachments');
  console.log(elem);
  elem.addEventListener('change', function(e) {
    console.log('Inside change eventlistener');
    console.log(e.target);
    var fileName = e.target.files[0].name;
    console.log(fileName);
  });
};

UPDATE: I am able to console the file names but still not able to display the names to the user. How do I show the names of the files within on the html page. elem.value = ... does not work.

Updated JS:

function getFileData() {
  console.log('Inside getFileData()...')
  var elem = document.getElementById('attachments');
  var files = document.getElementById('attachments').files;
  var names = '';
  for (let i = 0; i < files.length; i++) {
    console.log(files[i].name);
    names += files[i].name;
  }
  console.log(names);
  console.log(Object.keys(elem));
  //elem.setAttribute('value', names);

};
martinbshp
  • 1,073
  • 4
  • 22
  • 36
  • 2
    Adding an event listener inside an event listener is *almost always* a mistake. What is it that you expect to achieve by doing that? – Pointy Nov 16 '20 at 15:37
  • I am trying to achieve is get and display the file names of the files being uploaded. – martinbshp Nov 16 '20 at 15:50
  • Right by why add another event listener? It doesn't make sense; you already have an event listener. – Pointy Nov 16 '20 at 15:56

1 Answers1

2

You may try something like this

var elem = document.getElementById('attachments');
elem.addEventListener('change', getFileData);

function getFileData() {
  const files = this.files;
  const list = document.getElementById("result");
  let child;
  
  for ( let i = 0; i < files.length; i++) {
    child = document.createElement("li")
    child.textContent = files[i].name;
    
    list.append(child);
  }
}
<label>Attachments</label>
<div>
  <input type="file" class="form-control input-lg" name="attachments" id="attachments" multiple>
</div>

<ul id="result"></ul>