File Upload Event Binding

Is there a way to associate an event when the user selects a file to download and clicks β€œopen”, I want to trigger an event when the user clicks on it.

enter image description here

+4
source share
1 answer

In this case, 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 select the file.

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 verify that the item is available. Of course, this event can happen much later than it is really necessary, because they wait for all the elements on the page to be ready (and window.onload waits even more time for things, such as images to load). The option is to onchange handler immediately after the element on the page or at the end of the <body> .

+5
source

All Articles