Why doesn't IE reset the file input field?

I changed my current form to cause the form to be submitted after the user selects the file to upload. After the download is complete, I call:

$('#file').val(''); 

to reset the file input field.

 HTML <input name="file" type="file" id="file"/> 

This works in Chrome, FF and Safari, but does not work in IE. Is there a workaround or a better solution for IE?

+4
source share
1 answer

You cannot change the value of the file input type, as this will lead to a security vulnerability. Instead, just replace the file input with a new one. Instead of $('#file').val('') do the following:

 $('#file').replaceWith('<input name="file" type="file" id="file"/>'); 

It would be even better to clone a copy of the original version and store it in memory. When you need to replace it, just use the cloned copy and clone it again. So something like this:

 $(document).ready(function() { var empty_input = $('#file').clone(); $('#the-form').on('change', '#file', function(el) { $('#the-form').submit(); // assuming the target is a hidden iframe $(this).replaceWith(empty_input.clone()); }); }) 

Please note that I am using the delegated version with jQuery.on () , so the event will still work on the new input immediately after replacing it.

+6
source

Source: https://habr.com/ru/post/1384477/


All Articles