nicc96
nicc96

Reputation: 343

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:

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

Upvotes: 2

Views: 1412

Answers (2)

Saad Rehman
Saad Rehman

Reputation: 79

The easiest and working solution is that you do this in js func:

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;
  
    var file_input_label =  document.getElementById("file_input_label");
  file_input_label.classList.remove('CHOOSE_FILE_LABEL')
  next_sibling.innerText = file_name;
});

and add id to the label like this:

<label id="file_input_label" class="custom-file-label CHOOSE_FILE_LABEL BROWSE_BTN_LABEL" for="customFileInput"></label>

Hope that helps

Upvotes: 1

fdomn-m
fdomn-m

Reputation: 28611

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: '';}

Upvotes: 1

Related Questions