Created
February 23, 2015 07:48
-
-
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!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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'); |
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>
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'))
thank you.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hmm... does not seem to work today...