Creating a customized file input using CSS

I am currently utilizing Bootstrap4 to craft my webpage and I am incorporating a custom file input bar.

To retrieve the three labels of the input bar ("Choose file", "Browse", "Upload") from my stylesheet, I have created three custom classes with their corresponding content in the CSS file. See below:

.CHOOSE_FILE_LABEL::before{content: 'Choose file';}
.BROWSE_BTN_LABEL::after{content: 'Browse';}
.UPLOAD_BTN_LABEL::after{content: 'Upload';}
<div class="input-group">
  <div class="custom-file">
    <input type="file" class="custom-file-input" id="customFileInput">
    <label class="custom-file-label CHOOSE_FILE_LABEL BROWSE_BTN_LABEL" for="customFileInput"></label>
  </div>
  <div class="input-group-append">
    <button class="btn btn-success UPLOAD_BTN_LABEL" type="button" id="uploadBtn"></button>
  </div>
</div>

Subsequently, I aim to substitute the label of the input bar ("Choose file") with the filename once a file is selected. In order to achieve this, I use the following JavaScript code:

// Replace "Choose file" with the file name
document.getElementById("customFileInput").addEventListener('change', function (e)  
{
  e.preventDefault();
  var file_input = document.getElementById("customFileInput");
  var file_name = file_input.files[0].name;
  var next_sibling = e.target.nextElementSibling;
  next_sibling.innerText = file_name;
});

The issue lies in the fact that the selected file's name gets concatenated with (rather than replaced by) "Choose file". Is it possible to accomplish this through JavaScript or should I make modifications to my CSS file?

For the complete code, please refer to the following link: https://jsfiddle.net/5csLd90b/2/

Answer №1

In order to modify your file input to have the required attribute, you can utilize CSS and the :valid selector to style the label accordingly. Here is an example:

<input type="file" class="custom-file-input" id="customFileInput" required>
.custom-file-input:valid + .CHOOSE_FILE_LABEL::before{content: '';}

You can view the updated code on this fiddle: https://jsfiddle.net/50wqt4gx/

If you prefer not to use the required attribute, you can instead add a class using JavaScript to your file input element (or label) and then style the label with ::before based on that class. Here's an example:

file_input.classList.add("hasfile")
.custom-file-input.hasfile + .CHOOSE_FILE_LABEL::before{content: '';}

Answer №2

If you're looking for an easy and effective solution, consider implementing the following JavaScript function:

document.getElementById("customFileInput").addEventListener('change', function (e)  
{
  e.preventDefault();
  var file_input =  document.getElementById("customFileInput");
  var file_name = file_input.files[0].name;
  var next_sibling = e.target.nextElementSibling;
  
    var file_input_label =  document.getElementById("file_input_label");
  file_input_label.classList.remove('CHOOSE_FILE_LABEL')
  next_sibling.innerText = file_name;
});

To improve functionality, make sure to assign an id to the label element like this:

<label id="file_input_label" class="custom-file-label CHOOSE_FILE_LABEL BROWSE_BTN_LABEL" for="customFileInput"></label>

I hope this information proves helpful.

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

Change PHP code to a JSON file format

I am currently learning Laravel and my current focus is on how to send a JSON file from the back end to the front-end. I intend to utilize this JSON data to generate a graph. Within my model, I have created a function that retrieves values and timestamps ...

method for retrieving a single key-value pair from a JSON object

Suppose I receive a JSON object from the server using var oSer = new JavascriptSerializer(); var sJson = oSer.Serialize(myObject); The JSON returned to the client through an AJAX call is: "{\"IsValid\":false,\"EmployeeId\":null,&bsol ...

Encountering a "window not defined" error while implementing Leaflet in my Nuxt JS application

I'm encountering an issue while trying to generate my nuxt app, specifically on my 'Area' page. It seems like the error is related to the leaflet maps being used on this page. https://i.sstatic.net/Cj9ai.png Initially, I attempted to resol ...

Ionic utilized the $http service and was unexpectedly triggered two times

$scope.login = function(email,password){ $http({ method: 'POST', url: 'http://example.com/login', headers: { 'owner': $rootScope.secret }, data: {email:email, password:password } }).then(function successCallback(response) { co ...

Tips on updating Angular data model when a static HTML element changes

Currently, I am utilizing the editable-table jQuery plugin to enable editing in a table. This tool is simple to implement, lightweight, and highly efficient. The markup structure for this task looks like this: <tr ng-repeat="o in orders"> <td ...

Rendering a js.erb partial from one js.erb file to another using Rails and Jquery

Currently, I am facing a situation where I have duplicate js.erb code in the ajax responses of different models. To avoid this redundancy, I am looking to refactor the duplicate js.erb code by passing arguments into a js.erb partial. Can anyone guide me o ...

Learn how to smoothly transition between AJAX pages by toggling a class on click for a seamless animation

I am currently working on a practice project that involves loading each page via AJAX and displaying a fadeIn, fadeOut transition using CSS animation opacity. However, I am facing an issue where the addClass and removeClass functions are not being execute ...

The styling of the Material UI autocomplete listbox does not affect its appearance

I am working on an autocomplete feature that groups items by titles. I am trying to adjust the height of the first group to be different from the rest, but I am facing some challenges since there is no unique identifier for the ul component. To work around ...

Designing a Custom Wordpress Extension and Integrating External Scripts

As I dive into the world of WordPress plugin development, I'm seeking guidance from the codex to enhance my skills. Currently, I have a basic plugin that loads a javascript file from a CDN and is supposed to display tooltips. However, I'm facing ...

Choosing an element with JavaScript

var displayedImage = document.querySelector('.displayed-img'); var thumbBar = document.querySelector('.thumb-bar'); btn = document.querySelector('button'); var overlay = document.querySelector('.overlay'); /* Itera ...

A guide on using key arrows in JavaScript to navigate and focus on elements

When working on my HTML project, I have a list of elements that I want to be able to select using the arrow keys. I've included my code here for reference: [http://jsfiddle.net/T8S7c/] What I'm trying to achieve is when the arrow keys are press ...

Tips for adjusting the scrollbar in Tailwind (next.js/react)

Having trouble changing the appearance of my scrollbar in a single page application using Tailwind (react/next). I've attempted to create custom CSS for the first div in my index file, like so: <div className="no-scroll"> <<< ...

The day text function failed to return a value and instead gave back

I am having trouble figuring out where the mistake is in my function below. My goal is to retrieve the day value in string format. function getDayText(date){ var weekday = new Array(7); weekday[0]= "Sunday"; weekday[1] = "Monda ...

Troubleshooting: Issues with $oclazyload in AngularJS 1.5

I am currently encountering an issue with the implementation of $oclazyload to defer loading of my components. The code snippet below illustrates the setup: import angular from 'angular'; import uiRouter from 'angular-ui-router'; impor ...

Guide for building a Template-driven formArray in Angular

I am currently implementing a fixed number of checkboxes that are being bound using a for loop. <ul> <li *ngFor="let chk of checkboxes"> <input type="checkbox" [id]="chk.id" [value]="chk.value&q ...

Unable to `.catch()` an error while utilizing Jquery.ajax().then()

My current project involves making calls to various APIs using JQuery and caching the response from each API. This cached data is then used multiple times on the page to create different dashboard widgets. The issue I'm facing is that if an API retur ...

Determining age with calculator plugin using jQuery

I have two sets of dates (selected via inputs/selects in the format mm/dd/yyyy) on my page. I want a specific readonly text field to display the age in months, calculated based on those two dates, after a different select field (not part of the date set) ...

Utilize VueJS to bind a flat array to a v-model through the selection of multiple checkboxes

My Vue component includes checkboxes that have an array of items as their value: <div v-for="group in groups"> <input type="checkbox" v-model="selected" :value="group"> <template v-for="item in group"> <input type ...

Tick the checkboxes if they are found in the JSON data

After parsing this JSON object: [{"id_distrib":"1"},{"id_distrib":"44"},{"id_distrib":"4"}] I need to select the following checkboxes: <input id="1" class="cb_distrib_linux" type="checkbox"value="1">Achlinux <input id="2" class="cb_distrib_lin ...

What is the best way to combine a custom CSS class and a bootstrap class to style an element in next.js?

In the following example, the CSS class is imported and then applied to the element: import customStyles from "./Home.module.css"; <div className={(customStyles.collection, "card")}> Although they work individually, when combined as shown above, t ...