Although correct that onchange
event is triggered when you select a file with an input element, value
property of HTMLInputElement
with type="file"
will be a fake path such as C:\fakepath\image.jpg
.
As Jason P said,
val()
is a jquery function, but this
in your context is a DOM object.
Try this.value
or $(this).val()
On another note, as Humberto Corrêa pointed out,
if a user select the same image, the event will not be triggered because the current value is the same as the previous.
The fact is, even if the file content is different, the event might not occur unless the file name or size also has been changed.
Refer following code snippet if you want the input event to always trigger.
// Always fire input event on file inputs
// even when file name or size hasn't changed
var emptyFileList = $('<input type="file">').get(0).files;
$input.filter('[type=file]').on('click', function() {
// 1. Backup current file list
$(this).prop('originalFile', this.files);
// 2. Clear current file list
$(this).prop('files', emptyFileList);
}).on('input', function() {
// 3. If the new file list is empty, try to restore previous file list
if (this.files === emptyFileList) {
this.files = $(this).prop('originalFile');
}
});
this.files
is a FileList object containing all the files selected with the input.