I have a text field with placeholder text that says “No file chosen”. I wanted to add functionality to this so that if the text field is clicked it launches a file upload dialog. Then when a file is chosen, I want the name of the chosen file to appear in the text field.
This functionality can be described in several steps.
Step 1: Add a click event to the text field and have it open a file upload dialog
Set up a CDN for jQuery 3.3.
Set up the HTML with two input tags. The first one is the text field with placeholder text (input type=text). The second input is of (input type=file) and is styled to be invisible.
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" id="import-file-text-field" placeholder="No file chosen"> <input id="import-file-text-field-hidden" type="file" style="visibility: hidden;"/>
Next I set up a click even on the text field using jQuery:
$("#import-file-text-field").on("click", function(){ $("#import-file-text-field-hidden").trigger("click"); });
The action in this click event is a click trigger of the hidden input that is of type=file. This click action is what launches the file selection dialog.
Step 2: Add a jQuery onChange function to collect the selected file name
First we need to set up an onChange event function set to the hidden type=file input:
$("#import-file-text-field-hidden").on("change", function(e) {
Next set up a data variable to collect the name of the selected file:
let data = $("#import-file-text-field-hidden").prop('files')[0];
Here is a codepen that demonstrates this in action:
See the Pen click text field to launch file dialog – jQuery (simple) by Chris Nielsen (@Chris_Nielsen) on CodePen.0
Here is the complete jQuery, with comments:
// Click event set to detect click of the text field $("#import-file-text-field").on("click", function(){ // When a click occurs on the text field, launch the file selection dialog // input[type=file] $("#import-file-text-field-hidden").trigger("click"); }); // Change event set on the hidden input[type=file] input $("#import-file-text-field-hidden").on("change", function(e) { // get the first element of .prop('files') and place it in data let data = $("#import-file-text-field-hidden").prop('files')[0]; // Handle the case of no data if(!data) return; // Get some values related to the selected file // data.name is the name of the selected file data.fakepath = $("#import-file-text-field-hidden").val(); // put the name of the selected file into the text field $("#import-file-text-field").val( data.name ); // Show the full data related to the chosen file in the console console.log( data ); });
Here is a styled example on codepen:
See the Pen click text field to launch file dialog – jQuery by Chris Nielsen (@Chris_Nielsen) on CodePen.0