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/
2
Answers
If you can change your file input to be
required
then you can use CSS:valid
and next selector to target the label, eg: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:The easiest and working solution is that you do this in js func:
and add id to the label like this:
Hope that helps