Как очистить input type file
How can I clear an HTML file input with JavaScript?
I want to clear the file input in my form.
I know about setting the sources to the same method. But that method wont erase the selected file path.
Note: I would like to avoid having to reload the page, reset the form or perform an AJAX call.
19 Answers 19
There’s 3 ways to clear file input with javascript:
set value property to empty or null.
Works for IE11+ and other modern browsers.
Create an new file input element and replace the old one.
The disadvantage is you will lose event listeners and expando properties.
Reset the owner form via form.reset() method.
To avoid affecting other input elements in the same owner form, we can create an new empty form and append the file input element to this new form and reset it. This way works for all browsers.
I wrote a javascript function. demo: http://jsbin.com/muhipoye/1/
tl;dr: For modern browsers, just use
Old answer:
I still have to understand why this does not work with webkit.
Anyway, this works with IE9>, Firefox and Opera.
The situation with webkit is that I seem to be unable to change it back to file.
With IE8, the situation is that it throws a security exception.
Edit: For webkit, Opera and firefox this works, though:
(check the above answer with this proposal)
I’ll see if I can find a nice cleaner way of doing this cross-browser without the need of the GC.
Edit2:
Works with most browsers. Does not work with IE
Setting the value to » does not work in all browsers.
Instead try setting the value to null like so:
EDIT: I get the very valid security reasons for not allowing JS to set the file input, however it does seem reasonable to provide a simple mechanism for clearing already selecting output. I tried using an empty string but it did not work in all browsers, NULL worked in all the browsers I tried (Opera, Chrome, FF, IE11+ and Safari).
EDIT: Please note that setting to NULL works on all browsers while setting to an empty string did not.
Clearing using jQuery
Is it possible to clear an control value with jQuery? I’ve tried the following:
But it’s not working.
27 Answers 27
Easy: you wrap a Reset file Reset text
Quick answer: replace it.
In the code below I use the replaceWith jQuery method to replace the control with a clone of itself. In the event you have any handlers bound to events on this control, we’ll want to preserve those as well. To do this we pass in true as the first parameter of the clone method.
If cloning, while preserving event handlers, presents any issues you could consider using event delegation to handle clicks on this control from a parent element:
This prevents the need for any handlers to be cloned along with the element when the control is being refreshed.
Jquery is supposed to take care of the cross-browser/older browser issues for you.
This works on modern browsers that I tested: Chromium v25, Firefox v20, Opera v12.14
The following javascript solution also worked for me on the browsers mention above.
I have no way to test with IE, but theoretically this should work. If IE is different enough that the Javascript version does not work because MS have done it in a different way, the jquery method should in my opinion deal with it for you, else it would be worth pointing it out to the jquery team along with the method that IE requires. (I see people saying «this won’t work on IE», but no vanilla javascript to show how it does work on IE (supposedly a «security feature»?), perhaps report it as a bug to MS too (if they would count it as such), so that it gets fixed in any newer release)
Like mentioned in another answer, a post on the jquery forum
But jquery have now removed support for browser testing, jquery.browser.
This javascript solution also worked for me, it is the vanilla equivalent of the jquery.replaceWith method.
The important thing to note is that the cloneNode method does not preserve associated event handlers.
But jquery.clone offers this [*1]
[*1] jquery is able to do this if the events were added by jquery’s methods as it keeps a copy in jquery.data, it does not work otherwise, so it’s a bit of a cheat/work-around and means things are not compatible between different methods or libraries.
You can not get the attached event handler direct from the element itself.
Here is the general principle in vanilla javascript, this is how jquery an all other libraries do it (roughly).
Of course jquery and other libraries have all the other support methods required for maintaining such a list, this is just a demonstration.
как сбросить
Я разрабатываю приложение метро с VS2012 и Javascript
Я хочу сбросить содержимое моего файла ввода:
Как мне это сделать?
Решение jQuery, которое @ dhaval-marthak разместил в комментариях, очевидно, работает, но если вы посмотрите на реальный вызов jQuery, довольно легко увидеть, что делает jQuery, просто установив value атрибут в пустую строку. Так что в «чистом» JavaScript это будет:
Вам нужно завернуть в теги, а затем вы можете сбросить ввод, сбросив форму:
Это ЛУЧШЕЕ решение:
Из всех ответов здесь это самое быстрое решение. Нет входного клона, нет сброса формы!
Я проверял это во всех браузерах (он даже поддерживает IE8).
Если у вас есть следующее:
тогда просто сделайте:
сбросить управление файлом.
Вы можете просто клонировать его и заменить собой, со всеми прикрепленными событиями:
Другое решение (без выбора элементов HTML DOM)
Если вы добавили прослушиватель события ‘change’ на этот вход, то в коде javascript вы можете вызвать (для некоторых указанных условий):
РЕШЕНИЕ
Следующий код работал для меня с JQuery. Он работает в любом браузере и позволяет сохранять события и пользовательские свойства.
Смотрите этот jsFiddle для кода и демонстрации.
ССЫЛКИ
См. Как сбросить ввод файла с помощью JavaScript для получения дополнительной информации.
Есть несколько способов сделать это, но простой и понятный способ, который хорошо работает во многих браузерах, заключается в том, чтобы изменить значение поля на ноль, таким образом, поле загрузки будет сброшено, также попробуйте использовать чистый JavaScript, а не какую-либо инфраструктуру, я создал код ниже, просто проверьте его (ES6):
Особенно для угловых
Будет работать, но если вы используете Angular, он скажет, что «значение свойства» не существует для типа «HTMLElement’.any».
document.getElementById () возвращает тип HTMLElement, который не содержит свойства value. Итак, приведите его в HTMLInputElement
Однако мы не должны использовать манипуляции с DOM (document.xyz ()) в angular.
Для этого angular предоставил @VIewChild, @ViewChildren и т. Д., Которые являются document.querySelector (), document.queryselectorAll () соответственно.
Даже я не читал это. Лучше следить за блогами экспертов
How to reset ReactJS file input
I have file upload input:
And I handle upload this way:
If I upload same file twice, then upload event is not fired. How can I fix that? For simple js code it was enough to do the following: this.value = null; in change handler. How can I do it with ReactJS?
12 Answers 12
I think you can just clear the input value like this :
File input cannot be controlled, there is no React specific way to do that.
Edit For old browsers (
What worked for me was setting a key attribute to the file input, then when I needed to reset it I update the key attribute value:
That forces React to render the input again from scratch.
I do it by updating key inside my file input. This will force a re-render and previously selected file will go away.
Changing the state inputKey will re-render the component. One way to change the inputKey will be to always set it to Date.now() on click of a button which is supposed to clear the field.
With every click onClick you can reset the input, so that even with the same file onChange will be triggered.
The following worked for me using React Hooks. This is done using what is known as a «controlled input». That means, the inputs are controlled by state, or their source of truth is state.
TL;DR Resetting the file input was a two-step process using both the useState() and useRef() hooks.
NOTE: I also included how I reset a text input in case anyone else was curious.
Supporting Documentation:
Как я могу очистить ввод HTML файла с помощью JavaScript?
Я хочу очистить входной файл в моей форме.
Я знаю об установке источников в один и тот же метод. Но этот метод не стирает выбранный путь к файлу.
Примечание. Я бы хотел избежать перезагрузки страницы, reset формы или выполнить вызов AJAX.
ОТВЕТЫ
Ответ 1
Как удалить этот node, создав новый с тем же именем?
Ответ 2
Там 3 способа очистки ввода файла с помощью javascript:
значение свойства set равно пустому или нулевому.
Работает для IE11 + и других современных браузеров.
Создайте новый элемент ввода файла и замените старый.
Недостатком является то, что вы потеряете прослушиватели событий и свойства expando.
Reset форма владельца с помощью метода form.reset().
Чтобы избежать влияния на другие элементы ввода в одной и той же форме владельца, мы можем создать новую пустую форму и добавить элемент ввода файла в эту новую форму и reset. Этот способ работает для всех браузеров.
Я написал функцию javascript. demo: http://jsbin.com/muhipoye/1/
Ответ 3
tl;dr: для современных браузеров просто используйте
Старый ответ:
Мне все еще нужно понять, почему это не работает с webkit.
В любом случае, это работает с IE9>, Firefox и Opera.
Ситуация с webkit такова, что я не могу изменить его обратно в файл.
С IE8 ситуация такова, что он выдает исключение безопасности.
Изменить: Для webkit, Opera и Firefox это работает, хотя:
(проверьте приведенный выше ответ с этим предложением)
Я посмотрю, смогу ли я найти более понятный способ сделать этот кросс-браузер без GC.
Edit2:
Работает с большинством браузеров. Не работает с IE & lt; 9, это все.
Протестировано на Firefox 20, Chrome 24, Opera 12, IE7, IE8, IE9 и IE10.
Ответ 4
Итак, вот функция javascript vanilla, которую я написал, которая работает на FireFox (27 и 28), Chrome (33), IE (8, 9, 10, 11), Opera (17). это единственные браузеров, доступных в настоящее время для тестирования.
Ответ 5
Установка значения » не работает во всех браузерах.
Вместо этого попробуйте установить значение null следующим образом:
EDIT: Я получаю очень обоснованные причины безопасности, не позволяя JS устанавливать входной файл, однако представляется разумным предоставить простой механизм для очистки уже выбора вывода. Я попытался использовать пустую строку, но она не работала во всех браузерах, null работал во всех браузерах, которые я пробовал (Opera, Chrome, FF, IE11 + и Safari).
EDIT: Обратите внимание, что установка на null работает во всех браузерах при установке на пустую строку.
Ответ 6
U нужно заменить его новым вводом файла. Вот как это можно сделать с помощью jQuery:
и используйте эту строку, когда вам нужно очистить поле ввода (например, на каком-либо событии):
Ответ 7
РЕШЕНИЕ
Следующий код работал у меня с jQuery. Он работает в каждом браузере и позволяет сохранять события и настраиваемые свойства.
Смотрите этот jsFiddle для кода и демонстрации.
Ссылки
Ответ 8
Изменить:
Это не работает в IE и опера, но, похоже, работает для firefox, safari и chrome.
Ответ 9
У меня была такая же проблема, и я придумал это.
Ответ 10
Это на самом деле довольно легко.
Ответ 11
Вышеупомянутые ответы предлагают несколько неуклюжие решения по следующим причинам:
Кросс-браузер JS удобен, и кажется, что в этом случае слишком много неизвестных, чтобы надежно использовать переключение type (что опять-таки немного грязно) и установка value в »
Итак, я предлагаю вам решение на основе jQuery:
Он делает то, что он говорит, он заменяет ввод клоном сам по себе. Клон не будет иметь выбранный файл.
Результат: Счастливый программист
Ответ 12
Я искал простой и понятный способ очистки ввода HTML файла, приведенные выше ответы великолепны, но ни один из них действительно не отвечает на то, что я ищу, пока я не наткнулся в Интернете на простой и элегантный способ сделать это:
вся заслуга принадлежит Крису Койеру.
Ответ 13
Мне помогло то, что я попытался извлечь и загрузить последний выбранный файл, используя цикл, вместо очистки очереди, и это сработало. Вот код
Надеюсь, это поможет некоторым.
Ответ 14
Я перепробовал большинство решений, но, похоже, никто не работал. Однако я нашел прогулку вокруг этого ниже.
Поэтому моя стратегия такова: изначально button отправки отключена, после выбора файла атрибут disabled кнопки отправки будет удален, так что я могу отправить файл. После отправки я очищаю label которая выглядит так, будто я очищаю input файла, но на самом деле это не так. Затем я снова отключу кнопку отправки, чтобы запретить отправку формы.
Установив disable button disable или нет, я запрещаю отправку файла много раз, если не выберу другой файл.




