I have simple piece of code to upload files:
$(document).ready(function () { $(".attachmentsUpload input.file").change(function () { $('form').submit(); }); }); <form class="attachmentsUpload" action="/UploadHandler.ashx" method="post" enctype="multipart/form-data"> <input type="file" class="file" name="file" /> </form>
While I click on input and then select a file in dialog box, I'm submitting this file using ajax. This is not important part here. Important part is, that while I select the same file second time in the dialog box, just after submitting the first file, the .change() event does not fire in IE and Chrome. But while I choose different file, the event fires and works properly. Under Firefox it is firing all the time.
How to workaround this, to work as expected (as in Firefox) ?
This happens because the value of the input field (the selected filepath) does not change if you select the same file again.
You can set the value in the onChange()
event to an empty string and submit your form only if the value is not empty. Have a look at my sample and this jsFiddle Demonstration.
$(".attachmentsUpload input.file").change(function () { if ($(".attachmentsUpload input.file").val() == "") { return; } // your ajax submit $(".attachmentsUpload input.file").val(""); });
This, for any reason, does not work in IE9. You can replace the element to reset them. In this case you need jQuery live()
to bind the event, because your input field will dynamically (re)created. This will work in all browsers.
I found this solution on the stackoverflow answer Clearing input type='file' using jQuery
$(".attachmentsUpload input.file").live("change", function () { if ($(".attachmentsUpload input.file").val() == "") { return; } // get the inputs value var fileInputContent = $(".attachmentsUpload input.file").val(); // your ajax submit alert("submit value of the file input field=" + fileInputContent); // reset the field $(".attachmentsUpload input.file").replaceWith('<input type="file" class="file" name="file" />'); });
Note: live
is now removed from later versions of jQuery. Please use on
instead of live
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With