Transfer the name of the file from the upload to the text field

I am working on a form section that allows users to upload a file. I am looking to only have the filename sent to a text field within the same form. For example, if a user uploads "C:/Folder/image.jpg", I want the text field to display "image.jpg". I have attempted to write some code myself, but I am aware that there are errors:

function ff_uploadimages_action(element, action)
{var m = data.match(/((*):\/)/(.*)[\/\\]([^\/\\]+\.\w+)$/);
switch (action) {
case 'change':
if (data.match(/((*):\/)/(.*)[\/\\]([^\/\\]+\.\w+)$/).value)
ff_getElementByName('filename').value = m[2].text;
        default:;
    } // switch
} // ff_uploadimages_action

The ff_uploadimages field pertains to the file upload, while the filename field is where the name should be displayed. Any assistance would be greatly appreciated! Thank you.

Answer №1

Here is a method to achieve this

document.getElementById('upload').onchange = uploadOnChange;

function uploadOnChange() {
  var filename = this.value;
  var lastIndex = filename.lastIndexOf("\\");

  if (lastIndex >= 0) {
    filename = filename.substring(lastIndex + 1);
  }

  document.getElementById('filename').value = filename;
}
<input id="upload" type="file" />
<input id="filename" type="text" />


jQuery is not explicitly mentioned, but considering its widespread use, here is the same solution using jQuery

jQuery:

$('#upload').change(function() {
    var filename = $(this).val();
    var lastIndex = filename.lastIndexOf("\\");
    
    if (lastIndex >= 0) {
        filename = filename.substring(lastIndex + 1);
    }

    $('#filename').val(filename);
});

Demo:

http://jsfiddle.net/pxfunc/WWNnV/4/

Answer №2

Here is an example of HTML and JS code:

<input id="upload" type="file" onChange="uploadOnChange(this)" />
<input id="filename" type="text" />

And here is the corresponding JS function:

function uploadOnChange(e) {
    var filename = e.value;var lastIndex = filename.lastIndexOf("\\");
    if (lastIndex >= 0) {
        filename = filename.substring(lastIndex +1);
    }
    document.getElementById('filename').value = filename;
}

Answer №3

To simplify this process in jQuery, you can use the following method:

HTML Code:

<input type="file" id="inputFile" class="hidden"/>
<input type="text" id="inputDisplayFileName" readonly/>
<button id="buttonChooseFile">Choose file</button>

jQuery Code:

$("#buttonChooseFile").click(function()({
    $("#inputFile").click();        
});

$("#inputFile").change(function(){
    var fileName = $("#inputFile").prop('files')[0]["name"];

    $("inputDisplayFileName").val(fileName);
});

In this scenario, the default file upload option is hidden to allow for custom styling. When the button is clicked, it triggers the hidden file upload. Upon selecting a file, the .onchange() event handles the file copying to the read-only input field.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The jQuery function $.fn.myfunction appears to be malfunctioning

Here's the code I'm working with: [[A]] // jquery.fn.code (function( $ ){ $.fn.flash = function(duration) { this.animate({opacity:0},duration); this.animate({opacity:0},duration); }; })( jQuery ); 1. $(document).ready ...

Building an integrated Monaco editor using Electron and AngularJS

Struggling to integrate the Monaco editor into my Electron app. Despite following electron examples, encountering persistent errors in my application. The errors I'm facing include: "loader.js:1817 Uncaught Error: Unrecognized require call" "angula ...

When implementing tooltips in Apexchart's JavaScript, the y-axis second does not appear in the chart

Typically, when I append data to the second y-axis as an array, it works perfectly. However, for some reason, when I try to append a collection to the data, it no longer shows with two y-axes simultaneously. I even tried adding x and y as the Apex documen ...

Exploring nested elements in MongoDB with the help of Node.js API

In my current Node.JS API, I have a function written like this: Board.find({ users : req.user._id}) This function is designed to find all documents where the user's id is inside the array named users. For example, it will successfully fin ...

Access to PHP script (IF) unattainable following a POST occurrence

I'm completely new at this. I am attempting to create a contact form using HTML5 and PHP mail function, but I am facing an issue with my form action pointing to contacto.php. After submitting the form, it seems to be skipping over the IF condition wi ...

Tips for extracting Stripe response post payment using a client-side-only integration

My current component handles sending a payment order to my stripe account on the client-side. Everything seems to be working fine, but I'm struggling to find a way to retrieve the response or token from stripe containing the order details, which I nee ...

The updated Bootstrap 4 carousel is only working halfway as expected when attempting to double it up, causing the scroll loop to stop functioning

Discovering a fantastic carousel modification was an exciting find, which can be accessed Here. However, when attempting to place two carousels on one page, issues arose with the scrolling functionality. While I managed to make them operate on the correct ...

How to retrieve the value of a table row by clicking with the mouse using jQuery?

I am having an issue with my table data display. Each row in the table is assigned a unique ID, which corresponds to the value of the tr-tag. My goal is to log this ID in the console when a table row is clicked. Here is the table: $.getJSON(`http://local ...

Storing each item in its own document within a Firebase collection

I have a feature where users input their sitemap and it generates all the links in the sitemap. How can I then store each of those links in separate documents within a specific collection on Firebase? Below is the current function used to set data in Fir ...

Odd behavior of the "for in" loop in Node.js

It seems like I'm struggling with the use of the "for in" statement. When working with a JSON document retrieved from a mongodb query (using nodejs + mongoose), its structure looks something like this: [{ "_id":"596f2f2ffbf8ab12bc8e5ee7", "da ...

Implementing Formik in React for automatic updates to a Material-UI TextField when blurred

Presently, I am developing a dynamic table where users can simultaneously modify multiple user details in bulk (Refer to the Image). The implementation involves utilizing Material-UI's <TextField/> component along with Formik for managing form s ...

How can I use lodash to iterate through and remove whitespace from array elements?

I am currently working on a project involving demo lodash functionality, and I have encountered some unexpected behavior. Within an array of cars, there are various non-string elements mixed in. My goal is to iterate through each element of the array, rem ...

Disappearing Data in Chart.js When Window is Resized

I am utilizing the Chart.js library to present a line chart in a div that is enclosed within a <tr>. <tr class="item">...</tr> <tr class="item-details"> ... <div class="col-sm-6 col-xs-12 chart-pane"> <div clas ...

What is the proper way to reference a property's value within another property of the same JavaScript Object?

Within a Gulp.js file (or any Javascript file), I have defined paths in a Javascript object: var paths = { devDir : 'builds/development/', devDirGlobs : this.devDir+'*.html' } I am attempting to reference the pro ...

The outcome of the JQuery function did not meet the anticipated result

Here is the code I am using: $("p").css("background-color", "yellow"); alert( $("p").css("background-color")); The alert is showing undefined instead of the expected color value. I have tested this code on both Google Chrome and Firefox. Strangely, it w ...

Exploring the capabilities of chromaprint.js within a web browser

I'm currently in the process of developing a music streaming platform and I'm looking to include the chromaprint.js library for deduplication purposes. In my workflow, I utilize browserify and gulp. Despite the fact that the library claims it ca ...

Using checkboxes to select all in AngularJS

Recently, I started working with Angularjs and came across some legacy code. I am trying to figure out a way to select all checkboxes once the parent checkbox is selected. Here is the parent checkbox: <div class="form-group"> <label for="test ...

React Timer App: The setInterval function is being reset after each render operation

I'm currently working on a straightforward timer application that will begin counting seconds when a button is clicked. To implement this, I am utilizing react hooks. import React, { useState } from 'react' function Timer() { const [sec ...

Exploring the concept of data sharing in the latest version of Next.JS - Server

When using App Router in Next.JS 13 Server Components, the challenge arises of not being able to use context. What would be the most effective method for sharing data between various server components? I have a main layout.tsx along with several nested la ...

Include a lower border on the webview that's being shown

Currently, the webview I'm working with has horizontal scrolling similar to a book layout for displaying HTML content. To achieve this effect, I am utilizing the scroll function. My inquiry revolves around implementing a bottom border on each page usi ...