6

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.

enter image description here

2
  • 1
    the change event of the field should trigger in that occasion Commented Apr 12, 2013 at 15:25
  • could be duplicated. Check this stackoverflow.com/questions/4096335/… Commented Apr 12, 2013 at 15:26

1 Answer 1

6

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>.

Sign up to request clarification or add additional context in comments.

2 Comments

The window's onload wrapper is rather unnecessary if the script is placed in the end of the page/after the input element. =]
@FabrícioMatté True, but I don't like doing that and it's basically the same thing as being at the end of the body (a little different for window.onload, but still). And I don't exactly find that important related to this question. Nonetheless, I'll add a little tidbit about it in the answer. Thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.