简体   繁体   中英

Bootstrap 4 / jQuery - Clear filename in input field <input type='file' /> bs-custom-file-input

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.

There is no value to clear, the plugin generate a label for the custom-file what you see is not the input but the label, if you use your browser inspection you can see it, replace this:

// Clear the value
$('#customFile').val('');

by this:

// Clear the value, replace it by whatever text you want
$('#customFile').next('label').html('Select a file');

This works for a single field. It supports labels with child (for long names or multiple files)

function remove_selected(id_input){
   var fileInput = document.getElementById(id_input)
   fileInput.value = ''
   fileInput.dispatchEvent(new Event('change'));
}

remove_selected('file');

Source: https://github.com/Johann-S/bs-custom-file-input/issues/86

Try copying the HTML:

// At beginning
var div = $('.custom-file')[0]; // Or use an ID
var html = div.innerHTML;

// To clear the input
div.innerHTML = html;

It just remembers what the empty input field is like, and updates the code accordingly.

Keep in mind, everything within the div is reset. To prevent this, add an extra container around the input:

<div class="custom-file">
    <span id="customFileInputContainer">
        <input type="file" class="custom-file-input" id="customFile">
    </span>
    <label class="custom-file-label" for="customFile" data-browse="Browse">Select a file</label>
</div>

The JavaScript would need to change to accomadate this:

var div = $('#customFileInputContainer')[0];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM