Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to write custom-file-input text with css

I’m using Bootstrap4 to design my html page and I’m implementing a custom-file-input bar.

I want to get the three labels of the input bar ("Choose file", "Browse", "Upload") from my css file, so I’ve defined three custom classes and their content in the css file. Here is the code:

.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>

Then I want to replace the label of the input bar ("Choose file") with the name of the file when a file is selected. So I use the following JS code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// 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 problem is that the name of the selected file is concatenated with (and not replaced by) "Choose file". Can I do that with JS or should I change my css file?

Here is the full code: https://jsfiddle.net/5csLd90b/2/

>Solution :

If you can change your file input to be required then you can use CSS :valid and next selector to target the label, eg:

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

Updated fiddle: https://jsfiddle.net/50wqt4gx/

Otherwise you can add a class using js to your file input (or label) and apply ::before based on that class, eg:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading