javascript – Reset input file name and assign input text

Question:

I have the following code with an <input> of type text and another one of type file. See:

<form action="#" method="post" enctype="multipart/form-data">
    Name file:
    <input type="text" name="name" id="name"><br/><br/>
    <input type="file" name="file" id="file">
</form>

I would like to fill the input text with the name of the file loaded in the input file . What better way to do this?

Answer:

You can get the file name from .files[0].name , then just fill the text input with that value:

var inputNome = document.getElementById('name');
var inputFicheiro = document.getElementById('file');

inputFicheiro.addEventListener('change', function() {
  var nome = this.files[0].name;
  inputNome.value = nome;
});
<form action="#" method="post" enctype="multipart/form-data">
  Name file:
  <input type="text" name="name" id="name"><br/><br/>
  <input type="file" name="file" id="file">
</form>
Scroll to Top