hello I want to assign to the input with id assignFileName the name of the file of the input file csv.
I have it that way but it works until the second time
$( "#seleccionarArchivo" ).click(function() {
$( "#csv" ).click();
if( document.getElementById("csv").files.length == 0 ){
console.log("no files selected");
}else{
nombreArc = $( "#csv" ).val();
$('#asignarNombreArchivo').val(nombreArc);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-12 noPadding">
<label for="cv">
Adjunta tu CV
</label>
<div class="row">
<div class="col-12 col-sm-7 noPadding inputLeft">
<input type="text" placeholder="Elige tu archivo" id="asignarNombreArchivo">
</div>
<div class="col-12 col-sm-5 noPadding inputRight">
<input hidden type="file" name="csv" id="csv" accept="application/pdf, .doc, .docx, .odf" required>
<p href="#" class="btn btnTerciary btnFull" id="seleccionarArchivo">Buscar</p>
</div>
</div>
</div>
What happens is that the call to
click()
of the element#csv
does not wait for the user to finish selecting and close the dialog to return control to the program, but the next line is executed immediately.By the time the user presses the dialog's OK button , none of your code is running.
That is why you have the illusion that it doesn't work the first time but it does the second time, although the second time it will show you the file selected the first time, not the one selected the second time, because of what has already been said.
You can use the event
change
of theinput
to react to changes that occur in this control.Moving your code around, and putting everything in an initialization function, it looks like this: