Home > Back-end >  I Getting file names for the file upload element but i want replace that list when attached again
I Getting file names for the file upload element but i want replace that list when attached again

Time:08-15

Here i have code for taking info about attached files:

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


<script>
        

var elem = document.getElementById('upload-field');
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);
  }
}



</script>
        

but when I click on the button and attach the file - it shows this file info.

When I do it again code added this file info again under the previous text, and I would like to "reset" the list of files when I attach files again, but I don't know how to improve this code :(

CodePudding user response:

You forgot to add the <input type="file" id="upload-field"> to your example. If you wanted to reset the file control you would use a form around it. But since you wanted to "reset" the element, setting it's innerHTML to empty would suffice.

var elem = document.getElementById('upload-field');
elem.addEventListener('change', getFileData);

function getFileData() {
  const files = this.files;
  const list = document.getElementById("result");
  
  // empty list
  list.innerHTML = "";
  
  let child;

  for (let i = 0; i < files.length; i  ) {
    child = document.createElement("li")
    child.textContent = files[i].name;

    list.append(child);
  }
}
<input type="file" id="upload-field">
<ul id="result"></ul>

CodePudding user response:

That's great, thank You!

How it will be to show other way:

"You upload 1 file" and with multiple "You upload x files", counting script - like summary? :)

  • Related