Upload multiple files at once, edit span text, and retitle to files chosen

I need help updating the span text for each file uploader on my page. I want the default "Choose a file..." text to change to the selected filename.

Can someone assist me with this? Here is a Js fiddle that I've been working on.

This is my HTML markup:

<p class="hide_this last" style="display: none;">
  <span class="wpcf7-form-control-wrap file-05">
     <input type="file" name="file-05" size="40" class="wpcf7-form-control wpcf7-file" id="file-05" aria-invalid="false">
  </span>
  <label for="file-05"><span>Choose a file...</span></label><br>
  <a class="del_file" href="#">Remove</a>
</p>

This is my JS code:

//hide all inputs except the first one
$('p.hide_this').not(':eq(0)').hide();

//functionality for add-file link
$('a.add_file').on('click', function(e){
  //show by click the first one from hidden inputs
  $('p.hide_this:not(:visible):first').show('slow');
  e.preventDefault();
});

//functionality for del-file link
$('a.del_file').on('click', function(e){

//var init
var input_parent = $(this).parent();
var input_wrap = input_parent.find('span');

//reset field value
input_wrap.html(input_wrap.html());

//hide by click
input_parent.hide('slow');
e.preventDefault();
});

Answer №1

Click the following link to view the fiddle: Check out the fiddle here

  1. Utilize the change function to trigger events and retrieve file names.
  2. $(this).attr('id'); can be used to obtain the selector ID.

Jquery

 $(document).ready(function(){
            $('input[type=file]').change(function(){
          var filename = $(this).val().split('\\').pop();
            var idname = $(this).attr('id');
          $('.'+idname).next().find('span').html(filename);  
          });
      });

To shorten characters, check the updated fiddle below for a helpful function:

var str = "Hello Worsdfdsfsdfsdfsdfld!";
var length = str.length -20 ;
var n = str.substring(0, str.length- length );    
document.getElementById("demo").innerHTML = n;

Edit 2

For an updated version of the fiddle, click on this link: Fiddle update 2

 $(document).ready(function(){
                $('input[type=file]').change(function(){
                 var str= $(this).val().split('\\').pop();
                 var length = str.length -20 ;
                 var filename = str.substring(0, str.length- length );  
                var idname = $(this).attr('id');
              $('.'+idname).next().find('span').html(filename);  
              });
          });

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

How to Populate Object Literal with Multiple Objects in AngularJS

When I click on "Evan", I receive the following response: {"id":1,"name":"Evan"} If I click on "Robert", I will get: {"id":2,"name":"Robert"} Is there a way to modify this code so that it follows the aforementioned steps and generates an object similar ...

What could be causing AngularJS to truncate my URL in the search bar?

Currently, I am in the process of setting up a state provider for a CRUD website. One issue I encountered is that when I navigate to www.mysite.com/posts/mypost, the URL gets shortened to www.mysite.com/mypost and does not trigger the controller as intend ...

What methods are available to transfer a variable from one component to another in React?

In my React app, I have a form component that interacts with a PostgreSQL database to send data. Here is the script for my form: import bodyParser from 'body-parser'; import React, { Fragment, useState } from 'react'; import RatingStar ...

The code fails to execute within the specified time interval

I am trying to implement a jQuery code that calls every 5 seconds, but unfortunately the code is not working as expected. Here is my current implementation: setInterval($.getJSON('friendshipRequestCount', function(data) { var cnt=data. ...

Finding the host name of a client machine using Node.js

Is there anyone who can assist me in obtaining the client's machine name or host name for authentication on my website, which is operating internally within my company domain? I attempted the code below but received the server's host name instead ...

What is the best way to dynamically change the JSON-LD Script for the Schema?

Below is the script in question. Please read through it carefully. <script type="application/ld+json"> { "@context": "http://schema.org/", "@type": "Product", "name": "Bat, &q ...

An error has occurred: Expected a string as the element type in React when attempting to update the state

I encountered an issue while trying to update the state after fetching data. Error: Element type is invalid - expected a string (for built-in components) or a class/function (for composite components), but received: undefined. This could be due to forgett ...

I continue to encounter the same error while attempting to deliver data to this form

Encountering an error that says: TypeError: Cannot read properties of null (reading 'persist') useEffect(() => { if (edit) { console.log(item) setValues(item!); } document.body.style.overflow = showModal ? "hidden ...

Countdown to redirect or exit on Jquery mobile "pageshow" and "pagehide" events

Looking to implement a 30-second countdown on a Jquery Mobile page with specific requirements: (1) Countdown begins on pageshow (2) Redirects to new page when countdown expires (3) If user navigates away (pagehide) before countdown finishes, the timer fun ...

The method jqXHR.abort is not a valid function

I'm currently working on implementing a cancel button for jQuery file upload. Here is the code I have: var jqXHR = $('#fileupload').fileupload({ url: 'server/index.php', dataType: 'json', dropZone: $('#d ...

Which method is better for presenting data: PHP or JavaScript?

Currently, I am diving into vue.js on laracasts.com where Jeffrey Way demonstrates 2 ways to showcase data on a webpage. One method involves displaying data using Laravel foreach loops, while the other utilizes vue.js. This has led me to ponder: is there ...

Tips for retrying an insertion into the database when a duplicate unique value is already present

After thorough searching, I couldn't find any existing patterns. My goal is to store a unique key value in my MySQL database. I generate it on the server side using this code: var pc = require('password-creator'); var key = pc.create(20); ...

Plupload is not compatible with ng-dialog

I'm currently attempting to integrate plupload into a modal window that is generated by ng-dialog. Here is the code I am using: $scope.showManager = function(){ ngDialog.open({ template: '/template/fmanager.html', controller: &apo ...

What is the best method for enabling HTML tags when using the TinyMCE paste plugin?

After spending countless hours searching for a solution, I am still puzzled by this problem. My ultimate goal is to have two modes in my powerful TinyMCE editor: Allowing the pasting of HTML or Word/OpenOffice text with all styles and formatting attribu ...

The post page remains out of reach for Ajax

I've been struggling for hours to identify the issue with this code. I realized that I am unable to access the updateuser.php file even though it is in the same directory and the filenames are correct. Can someone please review the code below and let ...

Utilizing Multiple Components on a Single Page in React.js

I'm currently setting up a React main page that renders two separate components - Header and Test. render() { return ( <Header /> <Test /> ); } The Header component contains static content, while the ...

Spotfire: Changing a URL in an input field after it has been entered by the user

Currently, I am faced with a challenge related to importing a file in spotfire based on the path provided by the user. To accomplish this, I am utilizing a data function written in R script. In R, it is essential to note that all "\" characters are n ...

Error encountered: Element cannot be clicked on at specified coordinates - Angular/Protractor

Recently, I have been testing out CRUD functionality in an Angular app using Protractor. One recurring issue I've encountered is with the create/edit buttons, which all open the same modal regardless of the page you're on. The frustrating part i ...

Is there a guarantee that XHR requests made within a click handler of an anchor tag will always be sent?

I'm trying to find information on whether an XHR request triggered in an anchor tag's click event handler is guaranteed to be sent. Despite my attempts at searching, I can't seem to locate a definitive answer. The specific question I have i ...

Modifying the row background in a DataTables drawCallback

Is there a way to dynamically change the background color of a row based on a specific value in a cell using drawCallback? $(table_id).DataTable({ //... "drawCallback": function (settings) { // Here, if the type of data in a particular ce ...