5

I have html:

<form id="fileuploadform">
    <input type="file" id="fileupload" name="fileupload" />
</form>

and jquery:

$(':file').change(function(){
    var file = this.files[0];
    ...
});

The problem is: the change function fires only when the file selection is different than the selection made previously. That is of course the meaning of the 'change' event. I want my function to be called with the file dialog closes, no matter what.

I tried using 'select' event -- it never gets called

I also tried:

$(':file').bind('dialogclose', function(event) {
    alert('closed');
});

and:

$(':file').live("dialogclose", function(){
    alert('closed1');
}); 

They didn't work either.

Ian
  • 50,146
  • 13
  • 101
  • 111
Codegiant
  • 2,110
  • 1
  • 22
  • 31
  • 1
    http://jsfiddle.net/Xu55W/ - works on FF, maybe a browser-related issue. – Chris Dixon May 21 '13 at 15:39
  • @Chris Dixon This fires for all selection change. I need the event fires only when the file selection is different than the selection made previously. – Codegiant May 21 '13 at 15:42
  • 1
    @Codegiant Read the comment. It works in FireFox. If you select a file and Press OK, then go to select the same file again and press OK, the `change` event fires. It doesn't work in Chrome. And I'm not sure about other browsers. – Ian May 21 '13 at 15:43
  • 3
    @Codegiant Your comment completely contradicts what you've said in the question, so which is it that you actually want? – Anthony Grist May 21 '13 at 15:45
  • I don't think there is an event that will always fire when the file dialog closes, best you can do is a click event on the button that opens the dialog, or a change event, which if I remember correctly, should not fire unless the form elements value actually changes. – adeneo May 21 '13 at 15:54
  • This may be relevant: http://stackoverflow.com/questions/10214947/upload-files-using-input-type-file-field-with-change-event-not-always-firin – nullability May 21 '13 at 15:57

3 Answers3

11

I have faced the same issues when I used to work with jQuery dynamic appended HTML.

I would suggest you to use the below solution

$(document).on('input','#fileupload', function () {
  console.log('Your Code')
}); 
Umashankar
  • 694
  • 7
  • 21
6

try to use this code.

$('#fileupload').on('change', function () {
    alert('Hi');
    //do your function.
});

this function will call only you select different files otherwise not.

SanketS
  • 963
  • 1
  • 13
  • 36
6

I know this is an old post, but try using 'input' instead of 'change'. Worked for me. :)

$('#fileupload').on('input', function () {
  alert('Hi');
});
Ivan Town
  • 445
  • 8
  • 11
  • would you explain more, why input instead change? – Ravi Mane Sep 22 '17 at 14:24
  • I wish I could explain better. The jQuery implementation of the 'input' event seems to take from the JS implementation. Better written details here: https://stackoverflow.com/a/17384264/1735394 – Ivan Town Oct 18 '17 at 15:15