jQuery change method on input type=“file”

2019-01-08 11:51发布

问题:

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?

回答1:

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


回答2:

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


回答3:

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