Redeem input file name and assign input text

Asked

Viewed 1,587 times

5

I have the following code with a <input> text type and other 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’d like to fill in the input text with the file name uploaded to input file. What better way to do that?

3 answers

5


You can get the file name from the .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>

1

I don’t know if it is the best, but with jQuery it is possible to recover the files by 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>
<form action="#" 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>

0

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

If you set a name for your form, you will not need to select the input of the kind 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>
  • 2

    Rafael, about using document.formName.name, here: https://answall.com/a/123106/129

  • 1

    Thank you @Sergio

Browser other questions tagged

You are not signed in. Login or sign up in order to post.