Search code examples
javascriptjquerybootstrap-4input-field

Bootstrap 4 Custom file upload is not displaying the file name in label


I am trying to create file upload using the Bootstrap 4 custom-file . In this process file name is not getting displayed in the Label after the file is uploaded. I have tried using Javascript to update the file name in label. However this did not work. Below is the code. Please help me how to fix this.

<div class="container-fluid">
    <form enctype="multipart/form-data">
        <div class="card">
                    <div class="card-header">
                        BERICHT DATEI IMPORTIEREN
                    </div>
                    <div class="card-body">       
                            <div class="form-group">
                                    <div class="custom-file">
                                        <input type="file" class="custom-file-input" id="blkUploadReport" name="blkUploadReport">
                                        <label class="custom-file-label" for="blkUploadReport">Choose the File</label>
                                    </div>
                            </div>
                            <div class="form-group">
                                <div class="col-sm-offset-2 col-sm-6">
                                    <button class="btn btn-success btn-raised btn-sm" id="saveEdit" >
                                    IMPORTIEREN <span class="glyphicon glyphicon-floppy-disk"></span> 
                                    </button>                   
                                </div>  
                            </div>
                    </div>
        </div>
    </form>
</div> 
$('.custom-file-input').on('change', function(){
    console.log("I am inside upload event");
    files = $(this)[0].files; 
    name = ''; 
    for(var i = 0; i < files.length; i++)
    {
        name += '\"' + files[i].name + '\"' + (i != files.length-1 ? ", " : ""); 
    } 
    $(".custom-file-label").html(name);
});

Solution

  • The jQuery selector isn't selecting the input element. Use the id attribute of the file input instead.

    $('#blkUploadReport').on('change', function(){
        console.log("I am inside upload event");
        files = $(this)[0].files; 
        name = ''; 
        for(var i = 0; i < files.length; i++)
        {
            name += '\"' + files[i].name + '\"' + (i != files.length-1 ? ", " : ""); 
        } 
        $(".custom-file-label").html(name);
    })
    

    Demo: https://codeply.com/p/bJmnTUiqhS

    Also see: Bootstrap 4 File Input