jQuery change method on input type="file"

gurun8 picture gurun8 · Apr 27, 2010 · Viewed 229.9k times · Source

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?

Answer

Luis Melgratti picture Luis Melgratti · Apr 27, 2010

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(); });