Retrieve input file name and assign input text

4

I have the following code with a% text_type% and a file type. 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 populate the input text with the filename loaded in the input file . What better way to do this?

    
asked by anonymous 06.06.2017 / 21:20

3 answers

4

You can get the filename to .files[0].name , then just fill in the text input with this 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>
    
06.06.2017 / 21:24
1

I do not know if it is the best, but with jQuery it is possible to recover the files by the event change :

$('[name="file"]').on('change', function(){
  $('[name="name"]').val($(this)[0].files[0].name);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><formaction="#" method="post" enctype="multipart/form-data">
    Name file:
    <input type="text" name="name" id="name" readonly><br/><br/>
    <input type="file" name="file" id="file">
</form>
    
06.06.2017 / 21:26
0

Look for the element of type file in your form and store the name of it in a variable, then assign it to value of the input of type text .

If you set name to your form, you do not have to select input of type text with querySelector , simply use: document.formName.fieldName .

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

inputFicheiro.addEventListener('change', function() {
  document.formName.name.value = this.files[0].name;
  // Como seu input text tem o name de "name" utilize da mesma maneira.
});


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