Show the filename in the file upload field on Bootstrap 4

Utilizing Bootstrap 4 for my webpage, I have encountered an issue with the file upload option. When users select a file, the name of the file is not being displayed as it normally would in regular HTML. Can you please review my code and the accompanying screenshots to provide guidance on what needs to be adjusted?

<form method="post" action="upload_sub_fasta.php" enctype="multipart/form-data">
    <div class="input-group mb-3">
        <div class="custom-file">
            <input type="file" name="file" class="custom-file-input" id="validatedCustomFile" required>
            <label class="custom-file-label" for="validatedCustomFile">Choose query</label>
        </div>
        <button type="submit" name="submit" class="btn btn-primary">Upload</button>
    </div>
</form>

Below are the before and after screenshots of file selection:

Before file is selected

https://i.sstatic.net/jOgpy.png

After file is selected

https://i.sstatic.net/bPMNm.png

Thank you, Karthic

Answer №1

Make sure to include the following script in your code:

'use strict';

;( function ( doc, win, ind )
{
var elems = doc.querySelectorAll( '.custom-file-input' );
Array.prototype.forEach.call( elems, function( elem )
{
var label = elem.nextElementSibling,
labelVal = label.textContent;

elem.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.textContent = fileName;
else
label.textContent = labelVal;
});

// Fix for Firefox bug
elem.addEventListener( 'focus', function(){ elem.classList.add( 'has-focus' ); });
elem.addEventListener( 'blur', function(){ elem.classList.remove( 'has-focus' ); });
});
}( doc, win, 0 ));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<form method="post" action="upload_sub_fasta.php" enctype="multipart/form-data">
            <div class="input-group mb-3">
                    <div class="custom-file">
                            <input type="file" name="file" class="custom-file-input" id="validatedCustomFile" required>
                            <label class="custom-file-label" for="validatedCustomFile">Choose query</label>
                    </div>
                            <button type="submit" name="submit" class="btn btn-primary">Upload</button>
            </div>            

    </form>

Answer №2

Check out this code snippet that utilizes Bootstrap 4. You may have missed adding the necessary Javascript code. Give it a try, I believe it will assist you. Thank you.

$(".custom-file-input").on("change", function() {
  var fileName = $(this).val().split("\\").pop();
  $(this).siblings(".custom-file-label").addClass("selected").html(fileName);
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>

<div class="custom-file">
  <input type="file" class="custom-file-input" id="customFile" name="filename">
  <label class="custom-file-label" for="customFile">Choose file</label>
</div>

Answer №3

Feel free to experiment with this code and integrate it into your own CSS style:

<div class="input-group">
  <div class="input-group-prepend">
    <span class="input-group-text" id="inputGroupFileAddon01">Upload</span>
  </div>
  <div class="custom-file">
    <input type="file" class="custom-file-input" id="inputGroupFile01"
      aria-describedby="inputGroupFileAddon01">
    <label class="custom-file-label" for="inputGroupFile01"></label>
  </div>
</div>

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

Connecting HTML pages on two different drives on the same computer: Is it possible?

Is it possible to create hyperlinks between HTML pages located in two different folders on separate drives (for example, one in Drive:C and another in Drive:E) on the same computer? I can navigate up multiple directories and to different folders or subfol ...

Instructions on displaying the filename as the input for width and height dimensions

Running into an issue with Bootstrap 4 - whenever I try to upload a file with a long name, it ends up overflowing beyond the input field. ...

Creating a mandatory 'Select' component in Material UI with React JS

Is there a method to show an error message in red until a choice is selected? ...

What is the best way to configure an EmailId validator in Angular 6 to be case insensitive?

My register and login page include a form validator pattern matching for the registration form. this.registerForm = this.formBuilder.group({ firstName: ['', Validators.required], emailId: ['', [Validators.required, Validators.patt ...

Calculate the number of parent nodes and their respective child nodes

I am curious about how I can determine the number of children nested within parent-child relationships. For example: const parent = document.querySelectorAll('.parent'); parent.forEach(el => { const ul = el.querySelector('.child3-chi ...

Issue with deactivating attribute through class name element retrieval

There are multiple input tags in this scenario: <input type="checkbox" class="check" disabled id="identifier"> as well as: <input type="checkbox" class="check" disabled> The goal is to remov ...

Utilizing jQuery to access data stored locally

How can I retrieve and display all the values with key 'Task'? Below is the structure of the JSON data: {"Assignments":[{"AssignedBy":"537000","AssignedBy_FirstName":" JOHN","AssignedBy_LastName":"WANDER"}, {"AssignedBy":"537000","AssignedBy_Fir ...

When the only source is available, the image undergoes a transformation

Is there a way to dynamically adjust the height of an image using JQuery or JavaScript, but only when the image source is not empty? Currently, I have an image element with a fixed height, and even when there is no source for it, Chrome still reserves sp ...

When an HTML table utilizes both rowspan and colspan attributes, it may encounter issues with being overlapped by the

I'm working on a straightforward table that showcases the properties of a data element. Each row will represent an element from the AJAX response in a list format. The table is designed with "rowspan" and "colspan" to expand specific cells. However, ...

I would like to showcase the image with specific dimensions in CakePHP

Currently working on a CakePHP application where I need to upload an image. However, for some sections of my app, I need to display the image at a specific height and width without losing image quality. Any suggestions on how to achieve this? ...

AngularJS function orderBy reverses the array instead of sorting it

I encountered an issue where, after clicking the 'order button', the table does not order as expected. Instead, it reverses all the td elements. For example, 'A', 'C', 'B' becomes 'B', 'C', "A". I ...

"Encountering a problem with a function showing an undefined error

Trying to incorporate a slider feature into my application led me to reference this w3schools sample. However, upon loading the page, the images briefly appear before disappearing. Additionally, clicking on the arrow or dots triggers an error stating: U ...

Creating a bordered triangle using only CSS

Looking to create a message holder with a triangular tip bordered shape? I've successfully crafted the tip using two triangles: #triangle-border { width: 0px; height: 0px; border-style: solid; border-width: 0 100px 80px 100px; bor ...

Could Angular be automatically applying margins or padding to my component?

I'm encountering a minor issue.. I'm attempting to create a "Matrix" to construct a snake game in angular, but there seems to be an unremovable margin/padding. Below is my code: <!-- snake.component.html --> <div id="ng-snake-main&q ...

Creating a New Row in an HTML Table

Can someone provide guidance on how to insert a new row into an HTML table? I'm looking to have the first column contain a selection tool, and the second column hold a text box. Ideally, there would be a button below the table that, when clicked, add ...

Stylesheet compilation with SCSS scripts

I am facing an issue with prefix:css. I am not very familiar with the scss build process, so if anyone knows what the problem is, please help me out. "watch:sass": "node-sass src/styles/global.scss src/assets/css/style.css -w", ...

JavaScript script that parses innerHTML

Does the behavior of element.innerHTML = '<script>alert()</script>'; differ across browsers? Can I consistently expect innerHTML to not parse scripts? ...

"Dilemma with Displaying a 3-Digit Number in DaisyUI Using Next.Js Countdown Component

Hey there, I'm encountering an issue with the countdown component on my Next.js website using daisyUI. When the number of days exceeds 99, it's not rendering correctly as shown below: https://i.sstatic.net/cWR2tSEg.png https://i.sstatic.net/V0Iv ...

Enhance your iPad's design with a stylish div box-shadow

I'm in the process of developing a touch-optimized web application. As part of the design concept, I've implemented some visually appealing div elements that respond to clicks or touches for easy navigation. While this functionality works perfec ...

Variability of pixel dimensions on various devices

When it comes to front-end design in CSS, the use of pixels as a measurement is quite common. However, with varying display sizes and resolutions, one might wonder how relevant this fixed pixel size really is. Is there a way to utilize real-world measure ...