Reputation: 92
I am trying to create file upload using the Bootstrap 4 custom-file . In this process file name is not getting displayed in the Label after the file is uploaded. I have tried using Javascript to update the file name in label. However this did not work. Below is the code. Please help me how to fix this.
<div class="container-fluid">
<form enctype="multipart/form-data">
<div class="card">
<div class="card-header">
BERICHT DATEI IMPORTIEREN
</div>
<div class="card-body">
<div class="form-group">
<div class="custom-file">
<input type="file" class="custom-file-input" id="blkUploadReport" name="blkUploadReport">
<label class="custom-file-label" for="blkUploadReport">Choose the File</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-6">
<button class="btn btn-success btn-raised btn-sm" id="saveEdit" >
IMPORTIEREN <span class="glyphicon glyphicon-floppy-disk"></span>
</button>
</div>
</div>
</div>
</div>
</form>
</div>
$('.custom-file-input').on('change', function(){
console.log("I am inside upload event");
files = $(this)[0].files;
name = '';
for(var i = 0; i < files.length; i++)
{
name += '\"' + files[i].name + '\"' + (i != files.length-1 ? ", " : "");
}
$(".custom-file-label").html(name);
});
Upvotes: 1
Views: 2479
Reputation: 1
$(".custom-file-input").on("change", function() {
var fileName = $(this).val().split("\").pop();
$(this).siblings(".custom-file-label").addClass("selected").html(fileName);
});
Upvotes: 0
Reputation: 362440
The jQuery selector isn't selecting the input element. Use the id
attribute of the file input instead.
$('#blkUploadReport').on('change', function(){
console.log("I am inside upload event");
files = $(this)[0].files;
name = '';
for(var i = 0; i < files.length; i++)
{
name += '\"' + files[i].name + '\"' + (i != files.length-1 ? ", " : "");
}
$(".custom-file-label").html(name);
})
Demo: https://codeply.com/p/bJmnTUiqhS
Also see: Bootstrap 4 File Input
Upvotes: 1
Reputation: 979
If there are multiple files, I recommend creating an array using push
in javascript and then displaying them.
var name = []
for (var i = 0; i < files.length; i++) {
name.push(files[i].name) // Anything else you want to be displayed
}
document.getElementbyClassName('custom-file-label').innerHTML = name
Upvotes: 1