Nagy Vilmos
Nagy Vilmos

Reputation: 1918

jQuery listener on File upload button, when any file selected

I'd like to attach a function to my File upload button, when any file selected.

Now, I use the following code:

jQuery("input:file").change(function () {
    console.log("function");
});

This is OK, when the user selects the first file, or when she change it to an another file. But I'd like to run the script, when the user selects a file, and after that they open the dialog again, and select the same file second time.

What would be the correct jQuery event?

Thanks!

Upvotes: 0

Views: 3885

Answers (2)

Gass
Gass

Reputation: 9344

Minimalist

$("#myID").change(() => alert('It works!'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" id="myID">

Also

$("#myID").change(function(e){
  alert('It works!')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" id="myID">

Upvotes: 0

Machigatta
Machigatta

Reputation: 118

I would use the .on selector...

$(document).on('change','#inputFile' , function(){ 
  console.log("function");
});

Please check you input in the .on selector and after successfully running the function or even after a fail clean the input

$('#inputFile').val("");

Upvotes: 1

Related Questions