Reputation: 10056
Is there a way to bind an event when a user selects a file to upload and clicks on "open", I want to trigger the event when the user has clicked on open.
Upvotes: 6
Views: 9880
Reputation: 50933
In that scenario, the change
event will be fired.
If you have this HTML:
<input type="file" id="fileInput" />
Then use this JS:
window.onload = function () {
document.getElementById("fileInput").onchange = function () {
// this.value
};
};
(with the option of using addEventListener
/attachEvent
instead of setting the onclick
property)
Inside the handler, you can use this.value
to get the file selected.
Of course, with jQuery, you can use:
$(document).ready(function () {
$("#fileInput").on("change", function () {
// this.value OR $(this).val()
});
});
NOTE: The window.onload
and $(document).ready
handlers are used to make sure the element is available. Of course, this event can occur much later than actually necessary, since they wait for all elements on the page to be ready (and window.onload
waits even longer for things like images to be loaded). An option is to bind the onchange
handler immediately after the element on the page or at the end of the <body>
.
Upvotes: 6