I got a Bootstrap form with a recommended plugin to animate a custom file input: bs-custom-file-input. See: https://getbootstrap.com/docs/4.5/components/forms/#file-browser The form contains an input field (type="file") to add an attachment. If a user selects a file, which filesize is above 1MB, it shows an alert box with an error message.
How can I clear the filename in the input field after the error message?
Here is my code so far:
HTML form
<div class="container">
<div class="row">
<div class="col-md-12">
<form id="testform" method="post" enctype="multipart/form-data">
<div class="form-row">
<div class="form-group col-12">
<label for="customFile">Attachment</label>
<div class="custom-file">
<input type="file" class="custom-file-input" id="customFile">
<label class="custom-file-label" for="customFile" data-browse="Browse">Select a file</label>
</div>
</div>
</div>
</form>
</div>
</div>
$(document).ready(function() {
$('#customFile').on('change', function() {
// The recommended plugin to animate custom file input: bs-custom-file-input, is what bootstrap using currently
bsCustomFileInput.init();
// Set maximum filesize
var maxSizeMb = 1;
// Get the file by using JQuery's selector
var file = $('#customFile')[0].files[0];
// Make sure that a file has been selected before attempting to get its size.
if(file !== undefined) {
// Get the filesize
var totalSize = file.size;
// Convert bytes into MB
var totalSizeMb = totalSize / Math.pow(1024,2);
// Check to see if it is too large.
if(totalSizeMb > maxSizeMb) {
// Create an error message
var errorMsg = 'File too large. Maximum file size is ' + maxSizeMb + ' MB. Selected file is ' + totalSizeMb.toFixed(2) + ' MB';
// Show the error
alert(errorMsg);
// Clear the value
$('#customFile').val('');
// How to clear the filename in the input field?
alert('How to clear the filename in the input field?');
// Return FALSE
return false;
}
}
});
});
EDIT: working Fiddle: https://jsfiddle.net/Matti79/racv6w4d/15/
I've found an issue here: https://github.com/Johann-S/bs-custom-file-input/issues/37 but I can't make it work.