[javascript] Bootstrap 4 File Input

I am struggling with bootstrap 4 file browser. If I use custom-file-control I will see Choose file value all the time. https://v4-alpha.getbootstrap.com/components/forms/#file-browser

I would like to change the value of choose file after the file has been chosen. This value is actually hidden in css .custom-file-control:lang(en)::after and I do not know how to access and change it in javascript. I can get the value of chosen file like this:

document.getElementById("exampleInputFile").value.split("\\").pop();

not I need to change

.custom-file-control:lang(en)::after {
    content: "Choose file...";
}

somehow

link: http://codepen.io/Matoo125/pen/LWobNp

This question is related to javascript jquery css twitter-bootstrap bootstrap-4

The answer is


In case, if you need a no jquery solution

<label class="custom-file">
      <input type="file" id="myfile" class="custom-file-input" onchange="this.nextElementSibling.innerText = this.files[0].name">
      <span class="custom-file-control"></span>
</label>

With the help of jquery, it can be done like this. Code:

$("input.custom-file-input").on("change",function(){if(this.files.length){var filename=this.file[0].name;if(filename.length>23){filename=filename.substr(0,11)+"..."+filename.substr(-10);}$(this).siblings(".custom-file-label").text(filename);}});

In case you want to use it globally on all custom inputs use following jQuery code:

$(document).ready(function () {
    $('.custom-file-input').on('change', function (e) {
         e.target.nextElementSibling.innerHTML = e.target.files[0].name;
    });
});

For changing the language of the file browser:
As an alternate to what ZimSystem mentioned (override the CSS), a more elegant solution is suggested by the bootstrap docs: build your custom bootstrap styles by adding languages in SCSS
Read about it here: https://getbootstrap.com/docs/4.0/components/forms/#file-browser

Note: you need to have the lang attribute properly set in your document for this to work

For updating the value on file selection:
You could do it with inline js like this:

   <label class="custom-file">
      <input type="file" id="myfile" class="custom-file-input" onchange="$(this).next().after().text($(this).val().split('\\').slice(-1)[0])">
      <span class="custom-file-control"></span>
   </label>

Note: the .split('\\').slice(-1)[0] part removes the C:\fakepath\ prefix


As of Bootstrap 4.3 you can change placeholder and button text inside the label tag:

_x000D_
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
<div class="custom-file">_x000D_
  <input type="file" class="custom-file-input" id="exampleInputFile">_x000D_
  <label class="custom-file-label" for="exampleInputFile" data-browse="{Your button text}">{Your placeholder text}</label>_x000D_
</div>
_x000D_
_x000D_
_x000D_


 <!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">

    <title>Hello, world!</title>
  </head>
  <body>
    <h1>Hello, world!</h1>
  <div class="custom-file">
    <input type="file" class="custom-file-input" id="inputGroupFile01">
    <label class="custom-file-label" for="inputGroupFile01">Choose file</label>
  </div>
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
 <script>
$(function() {
  $(document).on('change', ':file', function() {var input = $(this), numFiles = input.get(0).files ? input.get(0).files.length : 1,
        label = input.val().replace(/\\/g, '/').replace(/.*\//, '');input.trigger('fileselect', [numFiles, label]);
  });
  $(document).ready( function() {
      $(':file').on('fileselect', function(event, numFiles, label) {var input = $(this).parents('.custom-file').find('.custom-file-label'),
      log = numFiles > 1 ? numFiles + ' files selected' : label;if( input.length ) {input.text(log);} else {if( log ) alert(log);}});
  });
});
 </script>
  </body>
</html>

Solution based on @Elnoor answer, but working with multiple file upload form input and without the "fakepath hack":

HTML:

<div class="custom-file">
    <input id="logo" type="file" class="custom-file-input" multiple>
    <label for="logo" class="custom-file-label text-truncate">Choose file...</label>
</div>

JS:

$('input[type="file"]').on('change', function () {
    let filenames = [];
    let files = document.getElementById('health_claim_file_form_files').files;

    for (let i in files) {
        if (files.hasOwnProperty(i)) {
            filenames.push(files[i].name);
        }
    }

    $(this).next('.custom-file-label').addClass("selected").html(filenames.join(',    '));
});

I just add this in my CSS file and it works:

.custom-file-label::after{content: 'New Text Button' !important;}



You can try below given snippet to display the selected file name from the file input type.

document.querySelectorAll('input[type=file]').forEach( input => {
    input.addEventListener('change', e => {
        e.target.nextElementSibling.innerText = input.files[0].name;
    });
});

Bootstrap 4.4:

Show a choose file bar. After a file is chosen show the file name along with its extension

<div class="custom-file">
    <input type="file" class="custom-file-input" id="idEditUploadVideo"
     onchange="$('#idFileName').html(this.files[0].name)">
    <label class="custom-file-label" id="idFileName" for="idEditUploadVideo">Choose file</label>
</div>

Bootstrap 4

More details are here https://learncodeweb.com/snippets/browse-button-in-bootstrap-4-with-select-image-preview/

Today I need to create a browse button with multi-upload files option all above snippets are not good for me.

The official Bootstrap example is also not working when I select multiple files.

I come up with this code may be will help others in the future.

<div class="container mt-5">
  <h1 class="text-center">Bootstrap 4 Upload multiple files</h1>
  <div class="col-sm-4 mr-auto ml-auto border p-4">
  <form method="post" enctype="multipart/form-data" action="upload.php">
    <div class="form-group">
      <label><strong>Upload Files</strong></label>
      <div class="custom-file">
        <input type="file" name="files[]" multiple class="custom-file-input form-control" id="customFile">
        <label class="custom-file-label" for="customFile">Choose file</label>
      </div>
    </div>
    <div class="form-group">
      <button type="submit" name="upload" value="upload" id="upload" class="btn btn-block btn-dark"><i class="fa fa-fw fa-upload"></i> Upload</button>
    </div>
  </form>
</div>

The js code is given below.

$(document).ready(function() {
  $('input[type="file"]').on("change", function() {
    let filenames = [];
    let files = document.getElementById("customFile").files;
    if (files.length > 1) {
      filenames.push("Total Files (" + files.length + ")");
    } else {
      for (let i in files) {
        if (files.hasOwnProperty(i)) {
          filenames.push(files[i].name);
        }
      }
    }
    $(this)
      .next(".custom-file-label")
      .html(filenames.join(","));
  });
});

The working code example is given here with bootstrap 3 and bootstrap 4.3.1.

https://codepen.io/mianzaid/pen/GeEbYV


I just solved it this way

Html:

<div class="custom-file">
   <input id="logo" type="file" class="custom-file-input">
   <label for="logo" class="custom-file-label text-truncate">Choose file...</label>
</div>

JS:

$('.custom-file-input').on('change', function() { 
   let fileName = $(this).val().split('\\').pop(); 
   $(this).next('.custom-file-label').addClass("selected").html(fileName); 
});

Note: Thanks to ajax333221 for mentioning the .text-truncate class that will hide the overflow within label if the selected file name is too long.


Without JQuery

HTML:

<INPUT type="file" class="custom-file-input"  onchange="return onChangeFileInput(this);">

JS:

function onChangeFileInput(elem){
  var sibling = elem.nextSibling.nextSibling;
  sibling.innerHTML=elem.value;
  return true;
}

KliG


Here is the answer with blue box-shadow,border,outline removed with file name fix in custom-file input of bootstrap appear on choose filename and if you not choose any file then show No file chosen.

_x000D_
_x000D_
    $(document).on('change', 'input[type="file"]', function (event) { _x000D_
        var filename = $(this).val();_x000D_
        if (filename == undefined || filename == ""){_x000D_
        $(this).next('.custom-file-label').html('No file chosen');_x000D_
        }_x000D_
        else _x000D_
        { $(this).next('.custom-file-label').html(event.target.files[0].name); }_x000D_
    });
_x000D_
    input[type=file]:focus,.custom-file-input:focus~.custom-file-label {_x000D_
        outline:none!important;_x000D_
        border-color: transparent;_x000D_
        box-shadow: none!important;_x000D_
    }_x000D_
    .custom-file,_x000D_
    .custom-file-label,_x000D_
    .custom-file-input {_x000D_
        cursor: pointer;_x000D_
    }
_x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
    <div class="container py-5">_x000D_
    <div class="input-group mb-3">_x000D_
      <div class="input-group-prepend">_x000D_
        <span class="input-group-text">Upload</span>_x000D_
      </div>_x000D_
      <div class="custom-file">_x000D_
        <input type="file" class="custom-file-input" id="inputGroupFile01">_x000D_
        <label class="custom-file-label" for="inputGroupFile01">Choose file</label>_x000D_
      </div>_x000D_
    </div>_x000D_
    </div>
_x000D_
_x000D_
_x000D_


For Bootstrap v.5

document.querySelectorAll('.form-file-input')
        .forEach(el => el.addEventListener('change', e => e.target.parentElement.querySelector('.form-file-text').innerText = e.target.files[0].name));

Affect all file input element. No need to specify elements id.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to twitter-bootstrap

Bootstrap 4: responsive sidebar menu to top navbar CSS class for pointer cursor How to install popper.js with Bootstrap 4? Change arrow colors in Bootstraps carousel Search input with an icon Bootstrap 4 bootstrap 4 responsive utilities visible / hidden xs sm lg not working bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js Bootstrap 4 - Inline List? Bootstrap 4, how to make a col have a height of 100%? Bootstrap 4: Multilevel Dropdown Inside Navigation

Examples related to bootstrap-4

Bootstrap 4 multiselect dropdown react button onClick redirect page bootstrap 4 file input doesn't show the file name How to use Bootstrap 4 in ASP.NET Core Bootstrap 4: responsive sidebar menu to top navbar CSS class for pointer cursor Change arrow colors in Bootstraps carousel Bootstrap 4 Dropdown Menu not working? Search input with an icon Bootstrap 4 How to import popper.js?