Skip to content

Instantly share code, notes, and snippets.

@Lochlan
Created February 23, 2015 07:48
Show Gist options
  • Save Lochlan/ccbe22e7c5e80b6d7966 to your computer and use it in GitHub Desktop.
Save Lochlan/ccbe22e7c5e80b6d7966 to your computer and use it in GitHub Desktop.
This is how you trigger a `change` event on `<input type="file">` with JavaScript — useful for testing!
// vanilla JS
var event = document.createEvent("UIEvents");
event.initUIEvent("change", true, true);
document.querySelector('input[type=file]').dispatchEvent(event);
// jQuery
$('input[type=file]').trigger('change');
@coolaj86
Copy link

Hmm... does not seem to work today...

@coolaj86
Copy link

Here's the 2021 version: https://stackoverflow.com/a/68737314/151312

<!-- an ugly file input (quick, hide it away!) -->
<input
    type="file"
    id="htmlFileInputElement"
    style="position: absolute; top: -1000px; left: -1000px;"
/>


<!-- a beautiful, inviting button -->
<button onclick="
    htmlFileInputElement.dispatchEvent(
        new MouseEvent('click', { bubbles: true })
    )
">Upload File</button>

@Sjeiti
Copy link

Sjeiti commented Nov 26, 2021

Here's the 2021 version

That does not trigger the 'change' event and can easily be accomplished without using any JavaScript:

<input
    type="file"
    id="inputFile"
    style="position: absolute; top: -1000px; left: -1000px;"
/>
<button><label for="inputFile">Look ma, no JS</label></button>

For triggering a change event you simply do this:

inputFile.dispatchEvent(new Event('change'))

@NazimMertBilgi
Copy link

thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment