Home > Back-end >  How to write custom-file-input text with css
How to write custom-file-input text with css

Time:10-13

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 >
  <div >
    <input type="file"  id="customFileInput">
    <label  for="customFileInput"></label>
  </div>
  <div >
    <button  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/

CodePudding user response:

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

CodePudding user response:

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"  for="customFileInput"></label>

Hope that helps

  • Related