我想清除我的表单中的文件输入。

我知道如何用同样的方法设置资源……但该方法不会擦除所选文件路径。

注意:我希望避免重新加载页面、重置表单或执行AJAX调用。

这可能吗?


当前回答

你需要用新的文件输入替换它。 下面是如何用jQuery完成的:

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

当你需要清除输入字段时使用这一行(例如在某些事件上):

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

其他回答

有3种方法用javascript清除文件输入:

将value property设置为空或空。 适用于IE11+和其他现代浏览器。 创建一个新的文件输入元素并替换旧的输入元素。 缺点是您将失去事件侦听器和expando属性。 通过form. Reset()方法重置所有者表单。 为了避免影响同一所有者表单中的其他输入元素,我们可以创建一个新的空表单,并将文件输入元素附加到这个新表单并重置它。这种方法适用于所有浏览器。

我写了一个javascript函数。演示: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);
        }
    }
}

我改变了类型文本和返回类型文件使用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");
}

这对我很管用。

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

tl;dr:对于现代浏览器,使用即可

输入。Value = "或输入。Value = null;


旧的回答:

如何:

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

我仍然要理解为什么这不能与webkit工作。

无论如何,这适用于IE9>, Firefox和Opera。 webkit的情况是,我似乎无法将其更改回文件。 在IE8中,情况是它抛出一个安全异常。

编辑: 对于webkit, Opera和firefox,这是有效的:

input.value = '';

(用这个建议核对上面的答案)

我将看看是否能找到一种更好、更干净的方法来跨浏览器执行此操作,而不需要GC。

Edit2:

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

适用于大多数浏览器。不工作与IE < 9,这是全部。 在firefox 20, chrome 24, opera 12, IE7, IE8, IE9和IE10上测试。

我也有同样的问题,我想出了这个。

var file = document.querySelector('input'); var emptyFile = document.createElement('input'); emptyFile。Type = 'file'; document.querySelector(“按钮”)。Onclick = function(){ 文件。文件= emptyFile.files; } <输入类型=“文件”> < >按钮明确> < /按钮