jQuery change method on input type="file"

JqueryFile UploadInputEvent HandlingOnchange

Jquery Problem Overview


I'm trying to embrace jQuery 100% with it's simple and elegant API but I've run into an inconsistency between the API and straight-up HTML that I can't quite figure out.

I have an AJAX file uploader script (which functions correctly) that I want to run each time the file input value changes. Here's my working code:

<input type="file" size="45" name="imageFile" id="imageFile" onchange="uploadFile()">

When I convert the onchange event to a jQuery implementation:

$('#imageFile').change(function(){ uploadFile(); });

the result isn't the same. With the onchange attribute the uploadFile() function is called anytime the value is changed as is expected. But with the jQuery API .change() event handler, the event only fires the first time a value is change. Any value change after that is ignored. This seems wrong to me but surely this can't be an oversight by jQuery, right?

Has anyone else encountered the same issue and do you have a workaround or solution to the problem other than what I've described above?

Jquery Solutions


Solution 1 - Jquery

is the ajax uploader refreshing your input element? if so you should consider using .live() method.

 $('#imageFile').live('change', function(){ uploadFile(); });

update:

from jQuery 1.7+ you should use now .on()

 $(parent_element_selector_here or document ).on('change','#imageFile' , function(){ uploadFile(); });

Solution 2 - Jquery

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live(). Refer: http://api.jquery.com/on/

$('#imageFile').on("change", function(){ uploadFile(); });

Solution 3 - Jquery

I could not get IE8+ to work by adding a jQuery event handler to the file input type. I had to go old-school and add the the onchange="" attribute to the input tag:

<input type='file' onchange='getFilename(this)'/>

function getFileName(elm) {
   var fn = $(elm).val();
   ....
}

EDIT:

function getFileName(elm) {
   var fn = $(elm).val();
   var filename = fn.match(/[^\\/]*$/)[0]; // remove C:\fakename
   alert(filename);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiongurun8View Question on Stackoverflow
Solution 1 - JqueryLuis MelgrattiView Answer on Stackoverflow
Solution 2 - Jquerymacio.JunView Answer on Stackoverflow
Solution 3 - Jqueryrodney hiseView Answer on Stackoverflow