I have a form whose only purpose is to upload files, but for user experience reasons, I need a nice-looking button that:
- loads the file dialog
- auto-submits the form when a file has been selected
The original solution was something like this JSFiddle, where you have a link that loads the file dialog, then listens for the dialog's change
event to auto-submit the form:
$("input[type=file]").on("change", function () {
// auto-submit form
$("form").submit();
});
$("#my-nice-looking-button").on("click", function (e) {
e.preventDefault();
// load file dialog
$("input[type=file]").trigger("click");
});
If you try that fiddle, it will work in IE9, Chrome, Firefox, etc., but it doesn't work in Internet Explorer 10. All the JavaScript functionality works, including the form's submit
event getting fired. But, the browser never POSTs the form data to the server; it just sits there.
Is there some security safeguard or file upload limitation built into IE10 that prevents this from working?
As it turns out, yes, IE10 does not let you both programmatically load a file dialog and automatically submit a form after a
change
event on a file dialog. Presumably one or the other will work, but not both. I haven't found any documentation to support this claim other than my own experimentation.The solution I found was to use CSS to style the file dialog's button such that it was invisible, but laid over the top of the nice-looking button, so that when you think you're clicking on the button, you're actually clicking on the file dialog's "select" button:
Then you just need to listen for the
change
event and submit the form as before:Doing this means that you are "organically" loading the file dialog, and IE10 lets it happen and allows you to auto-submit the form.
This solution also works in WebKit and Firefox.