Personalizing File Selection

What is the process for customizing file uploads?

<%= f.file_field :image, class: 'inputfile' %>
<label for="image">Choose an image</label>

I am looking to replace "choose an image" with "choose a file"

Answer №1

Your JavaScript code is missing the logic to retrieve the selected file name as shown in the tutorial:

var fileName = e.target.value.split( '\\' ).pop();

Update your JavaScript code to include this logic:

input.addEventListener( 'change', function( e ) {
  var inspiration_image = e.target.value.split( '\\' ).pop();
  if( inspiration_image ) {
    label.querySelector( 'span' ).innerHTML = inspiration_image;
  } else {
    label.innerHTML = labelVal;
  }
});

Full updated code snippet:

<%= file_field_tag :image, class: 'inputfile' %>
<label for="inspiration_image">Choose a file</label>

<script>
  var inputs = document.querySelectorAll( '.inputfile' );
  Array.prototype.forEach.call( inputs, function( input ) {
    var label  = input.nextElementSibling,
      labelVal = label.innerHTML;

    input.addEventListener( 'change', function( e ) {
        var fileName = '';
        if( this.files && this.files.length > 1 ) {
            fileName = ( this.getAttribute( 'data-multiple-caption' ) || '' ).replace( '{count}', this.files.length );
        } else {
            fileName = e.target.value.split( '\\' ).pop();
        }

        if( fileName ) {
            label.querySelector( 'span' ).innerHTML = fileName;
        } else {
            label.innerHTML = labelVal;
        }
    });
  });
</script>

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

After converting from php/json, JavaScript produces a singular outcome

After running a PHP query and converting the result to JSON using json_encode, I noticed that when I try to print the results using echo, only one entry from the query is output in JSON format. My objective is to make this information usable in JavaScript ...

How can I implement socket.io with multiple files?

I'm encountering an issue with Socket.io in my Express application. I am trying to have two .html files that can send messages to the server, but one of the files is throwing an error: Failed to load resource: net::ERR_FILE_NOT_FOUND add.html:26 Uncau ...

Using JavaScript to display content on the screen

As a newcomer to Javascript, I'm looking for a way to display my variable on the webpage without utilizing <span> or innerHTML. var pProductCode = $('[name=pProductCode]').val(); $('input[id*="_IP/PA_N_"]').each(function(i){ ...

How can we use Cypress to check if we are at the final slide in the presentation?

I am facing a challenge with multiple slideshow files that contain varying numbers of slides. Some have 10 slides, while others have 80 slides. My goal is to test every slide by using the forward and backward arrow buttons for navigation. Currently, I am c ...

retrieve data from an asynchronous request

Utilizing the AWS Service IotData within an AWS Lambda function requires the use of the AWS SDK. When constructing the IotData service, it is necessary to provide an IoT endpoint configuration parameter. To achieve this, another service is utilized to obta ...

In React, the `context` is consistently an empty object

I am facing an issue while trying to establish a context in my React App. For some reason, I am unable to access context from the children components. Here is the parent component: import React from 'react' import MenuBar from './MenuBar.js ...

Sending data as a string in an AJAX request

I have been struggling with this coffeescript function that controls dynamic select boxes. I am trying to pass the content of "modelsSelect" to another script, but for some reason, it's not working as intended. customScript.coffee dynamicSelection = ...

Problem with using puppeteer to interact with a dropdown menu

I have a project in which I am utilizing puppeteer to create a bot that can automatically check for my college homework assignments. The problem I am encountering is that when the bot tries to click on a dropdown menu, it fails and I receive an error messa ...

What is the best way to pass and save information across different routes in Express using Node.js?

Let's delve into the specific functionalities I envision for my server. Essentially, my project involves user registration and login processes. The URLs for these routes are as follows - localhost:3000/login and localhost:3000/register Upon successf ...

javascript trigger not functioning

Currently, I am working with ASP development and incorporating jQuery into my projects. One challenge I've encountered is not being able to utilize the trigger function upon page load. Interestingly, my change function seems to work smoothly, except ...

How to toggle the visibility of a div with multiple checkboxes using the iCheck plugin for jQuery

I customized my checkboxes using the icheck plugin to work with both single and multiple checkboxes, including a "Check all" option. Here is an example of how it looks in HTML: HTML : <div>Using Check all function</div> <div id="action" c ...

Transferring UTM parameters to a different page via a button click

Is there a way to extract parameters from a URL after the "?" and add them to a button's href in order to redirect to another landing page? I want to transfer UTM parameters to another page using JavaScript within the button. Original Homepage: Dest ...

Click on the links to view various captions for a single image, one at a time

My goal is to create an interactive image similar to what can be found at . (Click Play and navigate to page 5 to see the interactive physical exam). While this example seems to use Flash, I am interested in achieving a similar effect using javascript/jQue ...

How to Handle Jquery POST Data in Express Servers

Update Make sure to check out the approved solution provided below. I ended up fixing the issue by removing the line contentType: 'appliction/json', from my POST request. I'm facing a problem trying to send a string to Node.js/Express becau ...

Steps to develop a log-in API using Node.js

In the process of developing my web application, I have utilized node js exclusively for all functionalities and the web user interface has been successfully implemented. An issue that has come to light is that users are able to access the services API wi ...

Methods for removing and iterating through images?

I successfully programmed the image to move from right to left, but now I want to add a function where the image is deleted once it reaches x: 50 and redrawn on the left. I attempted to use control statements like "if," but unfortunately it did not work a ...

Is it advisable to initiate an AJAX call and allow the browser to cancel the request if needed?

When an AJAX request is made, it typically appears in the network tab in Chrome. However, if a client-based redirect occurs at the same time, the AJAX request may be cancelled. But does this mean that the request still reaches the server and executes as ...

Change web page in JavaScript using post data

Is there a method to utilize JavaScript for navigating to a new URL while including POST parameters? I am aware that with GET requests, you can simply add a parameter string to the URL using window.location.replace(). Is there a way to achieve this with ...

The React.js component search test encounters errors in locating components

I have been working on a React app that utilizes Redux and React-router. I am currently writing tests using React TestUtils, and I encountered an issue with the following test results: The first expect statement is successful: expect(nav).to.have.length(1) ...

Library written in JavaScript for extracting CSS that is relevant

Is there a JavaScript tool available that can extract the style information from HTML code? For instance, when given the following HTML snippet, it would output a style block containing all the computed styles applied to each of those elements? Input... ...