The file browser in Boostrap 4 is missing the file name. It just say Choose file... I made a javascript solution for it. Is there any better way to solve it?
HTML
<label class="file">
<input type="file" id="file1" >
<span class="file-custom" data-content="Choose file..."></span>
</label>
jQuery
$("input[type=file]").change(function(){
var fieldVal = $(this).val();
if (fieldVal != undefined || fieldVal != "") {
$(this).next(".file-custom").attr('data-content', fieldVal);
}
});
CSS
.file-custom:after {
content: attr(data-content);
}
The only difference is that you have to add data-content to the span. On the other hand it makes it easier to change language.
Link to Bootstraps file browser: http://v4-alpha.getbootstrap.com/components/forms/#file-browser
Looks like Bootstrap is now leaning towards not adding a JS solution for this and instead likely will be including something like your script in the documentation as a suggested implementation, based on mdo's comments here, where there is also a much more complete solution: https://github.com/twbs/bootstrap/issues/20813
I have updated your simple code for Bootstrap 4 Alpha 6.
jQuery
$("input[type=file]").change(function () {
var fieldVal = $(this).val();
if (fieldVal != undefined || fieldVal != "") {
$(this).next(".custom-file-control").attr('data-content', fieldVal);
}
});
CSS
.custom-file-control:after {
content: attr(data-content) !important;
}
Edit:
The above will show something like C:\\fakepath...
in the styled input, we can also get only the file name itself to show, using event.target.files[0].name
:
$("input[type=file]").change(function (event) {
var fieldVal = event.target.files[0].name;
if (fieldVal != undefined || fieldVal != "") {
$(this).next(".custom-file-control").attr('data-content', fieldVal);
}
});
Following up on Joey's answer, for Bootstrap 4 public release you would now use this JS and no CSS:
$("input[type=file]").change(function () {
var fieldVal = $(this).val();
if (fieldVal != undefined || fieldVal != "") {
$(this).next(".custom-file-label").text(fieldVal);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With