Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript file input onchange isn't triggered when they select a file with the same name

I have a file input in my webpage that allows a user to upload images.

I have things set up so that when they select an image, the change event of the file input is triggered and is shows them a preview of their image.

Sometimes once they see the preview they want to tweak the image a bit locally (eg using paint to crop it). They then click save in paint and click the file input and select the file again.

The problem is that when they select the file again, the change event of the input isn't triggered even though the image data has changed and if they try to upload the file to my server the old image data is used.

Is there any way to detect when the user actually selects a file, rather than when the file input change event occurs so that I can nicely deal with the case?

EDIT: Note that I can just delete and recreate a file input each time a user selects an image and this works but it means that the file input says 'no file chosen' which confuses the user.

like image 720
asutherland Avatar asked Jan 14 '23 16:01

asutherland


2 Answers

A simple solution is to do the following:

this.input.addEventListener('click', function() {
    this.value = '';
}, false);

This causes the change event to be triggered any time the user selects a file, because the initial click that opens the file browsing popup clears the input.

like image 177
asutherland Avatar answered Jan 25 '23 20:01

asutherland


this.input.bind('click', function() {
    this.value = '';
}, false);

instead of deprecated .addEventListener() try .bind()

like image 40
Jaylord Ferrer Avatar answered Jan 25 '23 21:01

Jaylord Ferrer