Search code examples
javascriptjqueryhtml

How to open select file dialog via js?


$('#id').click();

It doesn't work on Chrome 26 on Mac OS.

The problem actually is creation "upload" widget that can be integrated in a form. Widget will consists of two parts. The first part is div with initiator button and error/success messages. I think the way is put another form as the second part with file input and submit file into the iframe. After submition we fill hidden field in first part in main form or show errors in the same.

Easy way is adding file-form into main-form, but it's prohibited.


Solution

  • Using jQuery

    I would create a button and an invisible input like so:

    <button id="button">Open</button>
    <input id="file-input" type="file" name="name" style="display: none;" />
    

    and add some jQuery to trigger it:

    $('#button').on('click', function() {
        $('#file-input').trigger('click');
    });
    

    Using Vanilla JS

    Same idea, without jQuery (credits to @Pascale):

    <button onclick="document.getElementById('file-input').click();">Open</button>
    <input id="file-input" type="file" name="name" style="display: none;" />