buttonfile-uploadbootstrap-5jquery-file-upload

Bootstrap 5.3.5 Hide input[type='file'] with a button


I try to follow https://getbootstrap.com/docs/5.3/forms/input-group/#custom-file-input to hide the input[type='file'] with a button but it doesn't work.

<div class="input-group mb-3">
    <button class="btn btn-outline-secondary" type="button" id="btn-upload">Upload</button>
    <input id='image' name="image" type='file' class="form-control" accept="image/*" placeholder="Upload an image for your question" aria-describedby="btn-upload" aria-label="Upload" hidden>
</div>

There is no response clicking the button.


Solution

  • To get the desired result, you should use this code instead of using a <button> element in your code:

    <div class="input-group mb-3">
        <label class="input-group-text" for="inputGroupFile01">Upload</label>
        <input type="file" accept="image/*" class="form-control visually-hidden" id="inputGroupFile01">
    </div>
    

    When you click on a <label> that's linked to a hidden <input>, the browser automatically triggers the file picker.

    Even if the <input> is hidden (display: none or visually hidden), clicking the label will still open the file dialog!

    On the other hand, a <button> is not automatically associated with an <input>.

    The aria-describedby attribute only helps screen readers — it doesn’t create any click behavior.

    So when you click a button, nothing happens by default, because HTML doesn’t know you want it to open the file input.

    Quick note about using the 'hidden' attribute:

    If you want to completely remove an element from both the layout and screen readers, you can use the 'hidden' attribute.

    But if you want the input to still be accessible (for screen readers and forms), it’s better to use Bootstrap’s 'visually-hidden' class.