Input File change event not working

← PrevNext →

I recently noticed a bug in the Resize Multiple Images tool. The file input was not working (or not selecting files) after clearing the existing selections and selecting new files (images). The issue is now resolved. After a close investigation of the script, I found both onchange event and the jQuery change event were not triggering upon clearing the existing file selections and upon selecting the same image or file.

I am sure this might have happened to you too if you are working with files in your web application. It happens with file input onchange event (using JavaScript) and with jQuery $('#file').change(function () { } event.

A simple solution to get rid of this issue will be, to clear the file input value. I’ll show you how.

Let's see the bug (or the issue) first.

Here’s the file input element with the "onchange()" event.

<input  type="file" id="file" multiple onchange = "alert(this.value);" />
Try it

When you choose a file for the first time, it will alert and show the file detail. Choose the same file again, the onchange will not work and there is no alert message.

Note: Interestingly, I found this issue in Chrome and Safari browsers. "FireFox" however, responded well.

Something similar happened with jQuery change event. See this code 👇.

$(document).ready(function () {
	$('#file').change(function () {
      alert (this.files.length);
    });
});

To fix this issue (in JavaScript), you must set the file input value to null after performing some task. Like this,

<input  type="file" id="file" multiple 
    onchange = "alert(this.value); myFunction(); this.value = null;" />

Try it

Similarly, using jQuery...

$(document).ready(function () {
    $('#file').change(function () {
      alert (this.files[0].name);
      this.value = null;
    });
});
Try it

Do this with other events like the onclick() event or click event (in jQuery).

← PreviousNext →