The issue with displaying the file name in the Bootstrap 4 file input field is currently not resolved

Issue with file display in Bootstrap 4 custom-file-input class.

Here is the code being used:

<div class="input-group mb-3">
  <div class="custom-file">
    <input type="file" class="custom-file-input" id="inputGroupFile02">
    <label class="custom-file-label" for="inputGroupFile02">Choose file</label>
  </div>
  <div class="input-group-append">
    <button class="btn btn-primary">Upload</button>
  </div>
</div>

Looking for a simple solution to display the filename after selecting it?

Answer №1

To display the selected file name, you will need to utilize javascript, as outlined in the documentation: https://getbootstrap.com/docs/4.5/components/forms/#file-browser

For a direct solution, refer to this resource: Bootstrap 4 File Input

Below is the code snippet for your specific example:

<html lang="en">
    <head>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
        <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
    </head>
    <body>
        <div class="input-group mb-3">
            <div class="custom-file">
                <input type="file" class="custom-file-input" id="inputGroupFile02"/>
                <label class="custom-file-label" for="inputGroupFile02">Choose file</label>
            </div>
            <div class="input-group-append">
                <button class="btn btn-primary">Upload</button>
            </div>
        </div>
        <script>
            $('#inputGroupFile02').on('change',function(){
                // Obtain the file name
                var fileName = $(this).val();
                // Update the label with the selected file name
                $(this).next('.custom-file-label').html(fileName);
            })
        </script>
    </body>
</html>

Answer №2

Here is the code snippet I utilized:

<script type="application/javascript">
    $('input[type="file"]').change(function(e){
        var fileName = e.target.files[0].name;
        $('.custom-file-label').html(fileName);
    });
</script>

Answer №3

Anuja Patil's solution is designed to handle a single file input on a webpage, but it won't function properly if there are multiple file inputs present. In the case of multiple file inputs, this code snippet will display all selected files when the 'multiple' attribute is enabled.

<script type="text/javascript>

    $('.custom-file input').change(function (e) {
        var files = [];
        for (var i = 0; i < $(this)[0].files.length; i++) {
            files.push($(this)[0].files[i].name);
        }
        $(this).next('.custom-file-label').html(files.join(', '));
    });

</script>

It should be noted that

$(this).next('.custom-file-label').html($(this)[0].files.join(', '));
does not work as intended, hence the need for the for loop.

If you only anticipate working with a single file upload, a simpler alternative script can be utilized:

<script type="text/javascript>

    $('.custom-file input').change(function (e) {
        if (e.target.files.length) {
            $(this).next('.custom-file-label').html(e.target.files[0].name);
        }
    });

</script>

Answer №4

$(document).on('change', '.custom-file-input', function (event) {
    $(this).next('.custom-file-label').html(event.target.files[0].name);
})

This versatile solution works seamlessly with dynamically generated inputs, displaying the actual file name for a user-friendly experience.

Answer №5

Here is a solution that is compatible with Bootstrap 4.1.3:

<script>
    $("input[type=file]").change(function () {
        var fieldVal = $(this).val();

        // Modify the value to remove the fake path (Chrome)
        fieldVal = fieldVal.replace("C:\\fakepath\\", "");

        if (fieldVal != undefined || fieldVal != "") {
            $(this).next(".custom-file-label").attr('data-content', fieldVal);
            $(this).next(".custom-file-label").text(fieldVal);
        }
    });
</script>

Answer №6

Johann-S has come up with a fantastic solution that works like a charm. (It seems like he's the genius behind this incredible plugin)

If you take a look at the Bootstrap 4.3 documentation example page, you'll see that they are using Johann-S's plugin to customize the filename: https://github.com/Johann-S/bs-custom-file-input

To implement this feature in your project, make sure to utilize the Bootstrap custom file input classes. Simply add the plugin to your project and include the following code snippet in your script file on the webpage:

$(document).ready(function () {
  bsCustomFileInput.init()
})

Answer №7

For those looking to enhance their custom file input, consider utilizing the highly recommended Bootstrap plugin: https://www.npmjs.com/package/bs-custom-file-input

This versatile plugin can be implemented with or without jQuery and is compatible with React and Angular frameworks.

Answer №8

One way to handle multiple files is by displaying only the first file and indicating the number of hidden file names.

$('.custom-file input').change(function() {
    var $el = $(this),
    files = $el[0].files,
    label = files[0].name;
    if (files.length > 1) {
        label = label + " plus " + String(files.length - 1) + " additional files"
    }
    $el.next('.custom-file-label').html(label);
});

Answer №9

I have found a solution that works perfectly:

<script type="text/javascript">
    $('#elementID').on('change', function(e){
        var file = e.target.files[0].name;
        if (e.target.nextElementSibling !== null){
            e.target.nextElementSibling.innerText = file;
        }
    });
</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

How to retrieve a specific item from an array in JavaScript

I am retrieving this list from the server using PHP: ["Ak-Bulak","Balykchy","Batken"] How can I access it and insert it into select options using JavaScript? Here is what I have tried so far: for (var i in data) { $('#cities').append(' ...

Grunt tip: Converting jshint results to HTML format

I've set up jshint to run with grunt successfully, but now I'm looking to have the output in HTML format. Below is my grunt configuration: module.exports = function(grunt) { // Project configuration. grunt.initConfig({ jshint: { ...

How to use AJAX to retrieve the text content of an HTML option value?

I have a script that displays a list of values, which I want to write: <option th:each = "iName : ${iNames}" th:value = "${iName}" th:text = "${iName}" th:selected="${selectedIName == iName}" In addition, I have the function setSelectedName in my .j ...

Design a dynamic advertisement page using HTML and Bootstrap to ensure responsiveness

I am currently working on a marketing project where I want to give clients the ability to customize their landing page with image ads in a layout that looks something like this: -------------------------------------------------------------------------- | ...

Understanding how to sum the values of two separate dropdown selections using jQuery

Is it possible to combine and total up two different selections to display on the "Total" button below? I have added calculations to each selection. When a user selects a quantity, it should automatically sum up and display on the "Total" button, but I am ...

Modify the styling of the main webpage using the iframe

Can the CSS of a parent page be modified from an iframe when the parent page and iframe are hosted on separate domains? ...

Determining the Location of a Drag and Drop Item

I have been utilizing the code found at for implementing Drag & Drop functionality. My inquiry is: How can I retrieve the exact position (x,y) of a group once it has been dragged and dropped? ...

Is there a way to incorporate borders into JqTree?

I attempted the following .jqtree-tree .jqtree-element { border-color: black; border-width: 10px; } It seems that I may be overlooking certain elements to which this CSS should be applied ...

Issues with Bootstrap v4 in a Spring, Thymeleaf, and Java8 setup

While making the transition from bootstrap v3.3.7 to v4, I encountered a problem where the page was loading without any styles. I attempted different methods to fix this: Using CDN URLs (which worked, but wasn't ideal for me). Adding CSS/JS files lo ...

Tips for hiding a div element until its visibility is toggled:- Set the display property of

Looking for some guidance on this jQuery code I'm working with to create a toggle menu. The goal is to have the menu hidden when the page loads, and then revealed when a button is clicked. However, currently the menu starts off being visible instead o ...

Explore the Image Gallery feature that dynamically adjusts the width and height of images for optimal viewing experience

I am currently creating a unique photo gallery that showcases images uploaded by users. These images are resized to fit the gallery but can vary in dimensions from 100x100 to 2500x2500. The Photo Gallery View page I have designed is Fluid, meaning the wid ...

event handling for multiple dropdown lists using jQuery and Ajax

I have a situation where I am using two drop down menus to filter some results. When the user changes the option in the first drop down, it should dynamically update the choices in the second one. I managed to replace the options in the second drop down, b ...

What is the process for establishing a sleep time in jQuery?

I am looking to introduce a 2-second pause before window.location.href is executed. Here is an example: $.ajax({ url:"price", method:"POST", }).done(function (data) { var origin = window.location.origin; // I want to wait for ...

Removing files from a selection during a multi-file upload process in PHP

How can I remove file content from selected files during multiple file uploads and update the form after removing the file to send data to another PHP page using AJAX call function? I am inexperienced in handling multiple files. ...

Troubleshooting a malfunctioning PHP form that uses jQuery and AJAX

Snippet of HTML code: <form class="contact_form" action="" name="contact_form"> <ul><li> <input type="email" name="email" placeholder="Please enter your email here" required /> </li><li> <button class="submit" type=" ...

Personalize your Datatable export options with Jquery

I am working with a datatable that contains columns with data in the format 'XXXX unit'. For my export, I need to remove the 'unit' part of the data. What specific rule should I implement for this task? exportOptions: { columns: ...

Require the capability to bypass inline CSS styling

Currently facing an issue with a wordpress website I am constructing using iThemes Builder. The problem arises when integrating the plugin Jquery Megamenu, as the drop-down menu gets truncated due to an overflow:hidden property that cannot be overridden i ...

Make sure to keep Typed.js hidden until the Animate.css animation is complete

To create an engaging webpage, I am leveraging Bootstrap, Animate.css, and Typed.js. The desired effect is to have a blank page initially, then make the navigation bar slide down using animate.css fadeInDown. Once this animation completes, the Typed.js lin ...

Displaying JSP content within a <div> element with the help of JQuery

Here are the specifications for two important divs on my webpage. #apDiv1 { position:absolute; left:0px; top:115px; width:100%; height:100%; z-index:4; } #apDiv2 { position:relative; left ...

Can you explain the significance of "ml" in the context of Bootstrap 4?

Hey there, I'm currently testing out bootstrap4 beta. It seems to have replaced the classes pull-right and pull-left with ml-auto and mr-auto. I assume l stands for left and r stands for right. But what does m represent in this context? Could it be ma ...