Fixing Input File change event not working issue in JavaScript

By | November 17, 2020
Fixing Input File change event not working issue in JavaScript

I was working on a project and found that the input file change event was not working, whenever I select a file on the second or third times but if I was selecting the file the first time then it was working fine.

Why Input File change event not working issue occurs?

When we select a file by clicking on the input file tag, the file’s path gets stored into the ‘value’ attribute of the input file until the page is refreshed or the path gets removed programmatically and when we select the same file again then the JavaScript cannot identify either the input is changed or not.

How to fix Input File change event not working issue?

To fix this issue, you can add JavaScript code directly into HTML on the change event:

<form enctype='multipart/form-data'>
    <input onchange="alert(this.value); this.value=null;" type='file'>
</form>

Or you can write a JavaScript function to reset the input file and call the function on onChange event.

<form enctype='multipart/form-data'>
    <input onchange="alert(this.value); resetInputFile();" type='file'>
</form>

<script type="text/javascript">
function resetInputFile() {
	var input = document.getElementsByTagName('input')[0];
	input.value = null;
}
</script>

Note: I have tested this code on latest IE, Chrome and Firefox.

Leave a Reply

Your email address will not be published. Required fields are marked *