2012-03-08 45 views
31

下面是我有显示文件输入和一个“清除文件”按钮的jQuery代码的一部分。如何清除文件输入

var $imagefile = $('<input />').attr({ 
    type: 'file', 
    name: 'imageFile', 
    class: 'imageFile' 
}); 

$image.append($imagefile); 

var $imageclear = $('<input />').attr({ 
    type: 'button', 
    name: 'imageClear', 
    class: 'imageClear', 
    value: 'Clear File' 
}); 

$image.append($imageclear); 

现在我有“清除文件”按钮的原因是因为如果你点击按钮,那么它将清除文件输入中的任何东西。我怎么编码它,以便它在我点击“清除文件”按钮时实际清除文件输入?

+0

看到这个:http://stackoverflow.com/questions/1043957/clearing-input-type-file-using-jquery – 2012-03-08 12:41:53

+0

见这也https://forum.jquery.com/topic/how-要清除一个文件输入即ie – 2015-07-21 15:02:51

回答

74

这应该工作:

$imageClear.on('click', function() { 
    $imageFile.val(''); 
}); 
+1

这是否也适用于IE ... – 2012-03-08 12:40:25

+0

是的,它是一个*相对简单的* jQuery代码。这是一个跨浏览器的解决方案。 – 2012-03-08 12:45:59

+2

为了安全起见,在选择文件后,''是'readonly',这里是类似的[Q](http://stackoverflow.com/q/1043957/1548719)和记者[A](http://stackoverflow.com/a/1188853/1548719)提供的解决方案。 – 2012-08-01 07:36:52

5

这是我喜欢用为好方法,但我相信你需要的BOOL TRUE参数添加到克隆方法,以便对任何事件保持与附新的对象,你需要清除内容。

var input = $("#fileInput"); 

    function clearInput() { 
     input = input.val('').clone(true); 
    }; 

https://api.jquery.com/clone/

-1

本工程以

$("#yourINPUTfile").val(""); 
5

清除文件输入与jQuery

$("#fileInputId").val(null); 

清除文件输入用JavaScript

document.getElementById("fileInputId").value = null; 
0

我做了这样的事情,它的工作对我来说

$('#fileInput').val(null); 
0

另一种解决方案,如果你想成为肯定的是,这是能够跨浏览器是删除()标签,然后追加()或预先准备()或以某种其他方式重新添加具有相同属性的输入标记的新实例。

<form method="POST" enctype="multipart/form-data"> 
<label for="fileinput"> 
<input type="file" name="fileinput" id="fileinput" /> 
</label> 
</form> 

$("#fileinput").remove(); 
$("<input>") 
    .attr({ 
    type: 'file', 
    id: 'fileinput', 
    name: 'fileinput' 
    }) 
    .appendTo($("label[for='fileinput']"));