简体   繁体   English

如何使用 JavaScript 清除 HTML 文件输入?

[英]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.注意:我想避免重新加载页面、重置表单或执行 AJAX 调用。

Is this possible?这可能吗?

There's 3 ways to clear file input with javascript:有 3 种方法可以使用 javascript 清除文件输入:

  1. set value property to empty or null.将 value 属性设置为空或 null。

    Works for IE11+ and other modern browsers.适用于 IE11+ 和其他现代浏览器。

  2. Create an new file input element and replace the old one.创建一个新的文件输入元素并替换旧元素。

    The disadvantage is you will lose event listeners and expando properties.缺点是您将丢失事件侦听器和 expando 属性。

  3. Reset the owner form via form.reset() method.通过 form.reset() 方法重置所有者表单。

    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.我写了一个javascript函数。 demo: http://jsbin.com/muhipoye/1/演示: http : //jsbin.com/muhipoye/1/

function clearInputFile(f){
    if(f.value){
        try{
            f.value = ''; //for IE11, latest Chrome/Firefox/Opera...
        }catch(err){ }
        if(f.value){ //for IE5 ~ IE10
            var form = document.createElement('form'),
                parentNode = f.parentNode, ref = f.nextSibling;
            form.appendChild(f);
            form.reset();
            parentNode.insertBefore(f,ref);
        }
    }
}

tl;dr : For modern browsers, just use tl;dr :对于现代浏览器,只需使用

input.value = '';

Old answer:旧答案:

How about:怎么样:

input.type = "text";
input.type = "file";

I still have to understand why this does not work with webkit .我还是要明白为什么这符合webkit的工作。

Anyway, this works with IE9>, Firefox and Opera.无论如何,这适用于 IE9>、Firefox 和 Opera。
The situation with webkit is that I seem to be unable to change it back to file. webkit 的情况是我似乎无法将其改回文件。
With IE8, the situation is that it throws a security exception.使用 IE8,情况是它会引发安全异常。

Edit: For webkit, Opera and firefox this works, though:编辑:对于 webkit、Opera 和 firefox,这有效,但:

input.value = '';

(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.我会看看是否可以找到一种更简洁的方式来执行此跨浏览器,而无需 GC。

Edit2:编辑2:

try{
    inputs[i].value = '';
    if(inputs[i].value){
        inputs[i].type = "text";
        inputs[i].type = "file";
    }
}catch(e){}

Works with most browsers.适用于大多数浏览器。 Does not work with IE < 9, that's all.不适用于 IE < 9,仅此而已。
Tested on firefox 20, chrome 24, opera 12, IE7, IE8, IE9, and IE10.在 firefox 20、chrome 24、opera 12、IE7、IE8、IE9 和 IE10 上测试。

Setting the value to '' does not work in all browsers.将值设置为''不适用于所有浏览器。

Instead try setting the value to null like so:而是尝试将值设置为null如下所示:

document.getElementById('your_input_id').value= null;

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.编辑:我得到了不允许 JS 设置文件输入的非常有效的安全原因,但是提供一个简单的机制来清除已经选择的输出似乎是合理的。 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).我尝试使用空字符串,但它不适用于所有浏览器, NULL于我尝试过的所有浏览器(Opera、Chrome、FF、IE11+ 和 Safari)。

EDIT: Please note that setting to NULL works on all browsers while setting to an empty string did not.编辑:请注意,设置为NULL适用于所有浏览器,而设置为空字符串则不然。

Unfortunately none of the above answers appear to cover all the bases - at least not with my testing with vanilla javascript.不幸的是,上述答案似乎都没有涵盖所有基础 - 至少在我使用 vanilla javascript 的测试中没有。

  • .value = null appears to work on FireFox, Chome, Opera and IE11 (but not IE8/9/10) .value = null似乎适用于 FireFox、Chome、Opera 和 IE11(但不适用于IE8/9/10)

  • .cloneNode (and .clone() in jQuery) on FireFox appears to copy the .value over, therefore making the clone pointless. .cloneNode (和 jQuery 中的.clone() )似乎复制了.value ,因此使克隆变得毫无意义。

So here is the vanilla javascript function I have written that works on FireFox (27 and 28), Chrome (33), IE (8, 9, 10, 11), Opera (17)... these are the only browsers currently available to me to test with.所以这是我编写的适用于 FireFox(27 和 28)、Chrome(33)、IE(8、9、10、11)、Opera(17)的 vanilla javascript 函数……这些是目前唯一可用的浏览器给我测试。

function clearFileInput(ctrl) {
  try {
    ctrl.value = null;
  } catch(ex) { }
  if (ctrl.value) {
    ctrl.parentNode.replaceChild(ctrl.cloneNode(true), ctrl);
  }
}

The ctrl parameter is the file input itself, so the function would be called as... ctrl参数是文件输入本身,因此该函数将被称为...

clearFileInput(document.getElementById("myFileInput"));

SOLUTION解决方案

The following code worked for me with jQuery.以下代码适用于 jQuery。 It works in every browser and allows to preserve events and custom properties.它适用于每个浏览器,并允许保留事件和自定义属性。

var $el = $('#your-input-id');
$el.wrap('<form>').closest('form').get(0).reset();
$el.unwrap();

DEMO演示

See this jsFiddle for code and demonstration.有关代码和演示,请参阅此 jsFiddle

LINKS链接

document.getElementById('your_input_id').value=''

Edit:编辑:
This one doesn't work in IE and opera, but seems to work for firefox, safari and chrome.这个在 IE 和歌剧中不起作用,但似乎适用于 firefox、safari 和 chrome。

U need replace it with new file input.你需要用新的文件输入替换它。 Here is how it can be done with jQuery:以下是如何使用 jQuery 完成:

var inputFile = $('input[type=field]');
inputFile.wrap('<div />');

and use this line when you need to clear input field (on some event for example):并在需要清除输入字段时使用此行(例如在某些事件中):

inputFile.parent().html( inputFile.parent().html() );

the input.value = null is a working method, however it will only trigger input's change event if called from an onclick event. input.value = null是一种工作方法,但是如果从onclick事件调用它只会触发输入的change事件。

Solution to that would be calling that onchange handler manually whenever you need to reset the input.解决方案是在您需要重置输入时手动调用该onchange处理程序。

function reset_input(input) {
    $(input)[0].value = null;
    input_change_handler();
}
function input_change_handler() {
    // this happens when there's been a change in file selection

    if ($(input)[0].files.length) {
        // file(s) selected
    } else {
        // nothing is selected
    }
}
$(input).on('change', input_change_handler);

这其实很容易。

document.querySelector('#input-field').value = '';

I was having same problem and i came up with this.我遇到了同样的问题,我想出了这个。

 var file = document.querySelector('input'); var emptyFile = document.createElement('input'); emptyFile.type = 'file'; document.querySelector('button').onclick = function(){ file.files = emptyFile.files; }
 <input type='file'> <button>clear</button>

I have been looking for simple and clean way to clear HTML file input, the above answers are great, but none of them really answers what i'm looking for, until i came across on the web with simple an elegant way to do it :我一直在寻找简单而干净的方法来清除 HTML 文件输入,上面的答案都很棒,但它们都没有真正回答我正在寻找的问题,直到我在网上找到了一种简单而优雅的方法来做到这一点:

var $input = $("#control");

$input.replaceWith($input.val('').clone(true));

all the credit goes to Chris Coyier .所有的功劳都归功于Chris Coyier

 // Referneces var control = $("#control"), clearBn = $("#clear"); // Setup the clear functionality clearBn.on("click", function(){ control.replaceWith( control.val('').clone( true ) ); }); // Some bound handlers to preserve when cloning control.on({ change: function(){ console.log( "Changed" ) }, focus: function(){ console.log( "Focus" ) } });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="file" id="control"> <br><br> <a href="#" id="clear">Clear</a>

This worked for me.这对我有用。

const clear = (event) =>{event.target.value = [ ];}
clear("input_id"); 

Try this easy and it works试试这个简单的,它的工作原理

let input = elem.querySelector('input[type="file"]');
input.outerHTML=input.outerHTML;

this will reset the input这将重置输入

Here are my two cents, the input files are stored as array so here is how to null it这是我的两分钱,输入文件存储为数组,所以这里是如何将其归零

document.getElementById('selector').value = []

this return an empty array and works on all browsers这返回一个空数组并适用于所有浏览器

The above answers offer somewhat clumsy solutions for the following reasons:由于以下原因,上述答案提供了一些笨拙的解决方案:

  1. I don't like having to wrap the input first and then getting the html, it is very involved and dirty.我不喜欢必须先wrap input然后获取 html,它非常复杂和肮脏。

  2. Cross browser JS is handy and it seems that in this case there are too many unknowns to reliably use type switching (which, again, is a bit dirty) and setting value to ''跨浏览器 JS 很方便,在这种情况下,似乎有太多的未知数无法可靠地使用type切换(这又有点脏)并将value设置为''

So I offer you my jQuery based solution:所以我为您提供我的基于 jQuery 的解决方案:

$('#myinput').replaceWith($('#myinput').clone())

It does what it says, it replaces the input with a clone of itself.它做它所说的,它用它自己的克隆替换输入。 The clone won't have the file selected.克隆不会选择文件。

Advantages:好处:

  1. Simple and understandable code简单易懂的代码
  2. No clumsy wrapping or type switching没有笨拙的包装或类型切换
  3. Cross browser compatibility (correct me if I am wrong here)跨浏览器兼容性(如果我错了,请纠正我)

Result: Happy programmer结果:快乐的程序员

What helped me is, I tried to fetch and upload the last selected file using a loop, instead of clearing out the queue, and it worked.对我有帮助的是,我尝试使用循环获取和上传最后一个选定的文件,而不是清除队列,并且它起作用了。 Here is the code.这是代码。

for (int i = 0; i <= Request.Files.Count-1; i++)
{
 HttpPostedFileBase uploadfile = files[i];
 Stream fs = uploadfile.InputStream;
 BinaryReader br = new BinaryReader(fs);
 Byte[] imageBytes = br.ReadBytes((Int32)fs.Length);
}

Hope this might help some.希望这可以帮助一些人。

I tried most of solutions but did not seem anyone to work.我尝试了大多数解决方案,但似乎没有人工作。 However I found a walk around for it below.但是我在下面找到了它的走动。

The structure of the form is: form => label , input and submit button .表单的结构是: form => labelinputsubmit button After we choose a file, the filename will be shown by the label by doing so manually in JavaScript.在我们选择一个文件后,文件名将通过在 JavaScript 中手动执行来显示在标签上。

So my strategy is: initially the submit button is disabled, after a file is chosen, the submit button disabled attribute will be removed such that I can submit file.所以我的策略是:最初禁用提交button ,选择文件后,将删除提交按钮disabled属性,以便我可以提交文件。 After I submit, I clear the label which makes it look like I clear the file input but actually not.提交后,我清除了label ,这使它看起来像我清除了文件input但实际上并没有。 Then I will disable the submit button again to prevent from submitting the form.然后我将再次禁用提交按钮以防止提交表单。

By setting the submit button disable or not, I stop the file from submitted many times unless I choose another file.通过设置提交button disable与否,我会多次停止提交文件,除非我选择另一个文件。

I changed to type text and back to type to file using setAttribute我改为使用 setAttribute 输入文本并返回输入到文件

'<input file-model="thefilePic" style="width:95%;" type="file" name="file" id="filepicture" accept="image/jpeg" />'

'var input=document.querySelector('#filepicture');'

if(input != null)
{
    input.setAttribute("type", "text");
    input.setAttribute("type", "file");
}

An - in my world easy an clean solution - is, to set the file inputs files to a clear FileList .一个 - 在我的世界中简单的一个干净的解决方案 - 是将文件输入 files 设置为清晰的FileList

EDIT: as SteJ told - this ist not working with Safari.编辑:正如 SteJ 所说 - 这不适用于 Safari。

Since we can not create a FileList directly - I user DataTransfer as "hack"由于我们无法直接创建FileList - 我将DataTransfer用作“hack”

@$input[0].files=new DataTransfer().files 

or或者

file_input_node.files=new DataTransfer().files 

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.注意:我希望避免重新加载页面,重置表单或执行AJAX调用。

Is this possible?这可能吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 HTML如何使用javascript清除输入? - HTML how to clear input using javascript? 如何通过Javascript清除HTML输入文本框 - How to clear HTML input textbox via Javascript 如何清除Enter或换行符(html / javascript)的文本框? - How can I clear a text box of enter or newline (html / javascript)? HTML5 JavaScript,如何在每次按下空格键时清除我的输入字段,使输入字段中最多只显示 1 个单词? - HTML5 JavaScript, How can I clear my input field every time I hit the spacebar so there is only ever max 1 word showing in the input field? 如何将输入框(html 文件)中的值传递给 javascript 注入文件(inject.js)? - How can I pass a value from an input box (html file) to a javascript inject file (inject.js)? 如何用javascript清除输入? - How to clear an input with javascript? 通过JavaScript克隆html元素后,如何清除输入字段并选择字段? - How do I clear input fields and select fields after cloning html elements via JavaScript? 如何清除datetimepicker上的输入文本? - How can I clear input text on datetimepicker? 如何清除AngularJS中的输入字段 - How can I clear the input field in AngularJS 为什么这个 html javascript 文件不起作用,我怎样才能让用户输入不是正数? - why this html javascript file doesnt work and how can i make user input to not be anything but positive number?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM