2

I have bound two separate events for testing, but for whatever reason neither of them are triggering when I select a file. I'm sure I have just not had enough coffee today but it seems to be the correct way of detecting file selection.

HTML:

<input type="file" id="files">

JS:

$(document).on("ready", function() {

    $("#files").on("change", function() {
        alert("Files changed.");
    });

    $(document).on("change", "#files", function() {
        alert("Files changed.");
    });

});

example: https://jsfiddle.net/snoapps/66y45hjh/

2 Answers 2

6

https://jsfiddle.net/66y45hjh/2/

Your second function was correct but the way the functions are nested wouldn't let it execute the way you wanted it to. Take a look at the edit I made to your fiddle.

The javascript code I used was as follows.

$(function() {
    $(document).on("change", "#files", function() {
        alert("Files changed.");
    });
});
Sign up to request clarification or add additional context in comments.

3 Comments

Could you please explain the downvote? The code works as it is supposed to.
This works, what's the point of using the $(function() {}); in the script? (p.s. I don't know who downvoted, it wasn't me)
$(function() {}); is just a simplified way of writing out $('document').ready(function(){}); It's best practice to execute trigger events within it to be sure that the document is fully loaded before a user fires the event
3
  1. It's $('document').ready(function(){}); https://api.jquery.com/ready

  2. You don't need your second function

So:

$(document).ready(function() {

    $("#files").on("change", function() {
        alert("Files changed.");
    });


});

1 Comment

Thanks, I didn't know that on("ready" became deprecated in 1.8, both answers work for me, but Alex answered first

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.