我得到了一个带有推荐插件的 Bootstrap 表单,用于为自定义文件输入设置动画: bs-自定义文件输入 .见:https://getbootstrap.com/docs/4.5/components/forms/#file-browser
该表单包含一个用于添加附件的输入字段 (type="file")。
如果用户选择一个文件大小超过 1MB 的文件,它会显示一个带有错误消息的警告框。
错误消息后如何清除输入字段中的文件名?
到目前为止,这是我的代码:
HTML 表单
<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;
}
}
});
});
编辑:工作 fiddle :
https://jsfiddle.net/Matti79/racv6w4d/15/
我在这里发现了一个问题:https://github.com/Johann-S/bs-custom-file-input/issues/37但我不能让它工作。
最佳答案
没有要清除的值,插件为自定义文件生成一个标签,您看到的不是输入而是标签,如果您使用浏览器检查可以看到它,请替换为:
// Clear the value
$('#customFile').val('');
这样 :
// Clear the value, replace it by whatever text you want
$('#customFile').next('label').html('Select a file');
关于javascript - Bootstrap 4/jQuery - 清除输入字段中的文件名 <input type ='file'/> bs-custom-file-input,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62203016/