2

Need to do an operation when the file is changed or when we clear the file input.

$('input[type="file"]').change(function (e) {
       console.log('changed')
});

It works when I select/change the file.

It doesn't trigger change event when I clear the input[type=file].

$('input[type="file"]').val('');

Does clearing the value triggers the change event? or what would be a better way to this?

ejaz
  • 333
  • 2
  • 15
  • 2
    If you are programmatically clearing the value like the above example, you can just call $('input[type="file"]').trigger("change"); right after that value is cleared. – Asyranok Mar 19 '19 at 15:28
  • Or better yet, just directly call the `change` callback. – Scott Marcus Mar 19 '19 at 15:29
  • @Asyranok Yes, this can be done. So clearing the input doesn't trigger change event? Need to explicitly trigger the 'change' event. right? – ejaz Mar 19 '19 at 15:34

1 Answers1

5

You can force to trigger the event change

 $('input[type="file"]').val('').trigger('change');
R3tep
  • 12,512
  • 10
  • 48
  • 75