如何清除文件输入


82

以下是我具有的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);

现在,我拥有“清除文件”按钮的原因是,如果单击该按钮,它将清除文件输入中的所有内容。我如何编码它,以便当我单击“清除文件”按钮时,它实际上清除了文件输入?



Answers:


155

这应该工作:

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

1
是的,这是一个相对简单的jQuery代码。这是一个跨浏览器的解决方案。
Guillaume Poussel

3
伙计们,<input type=file />readonly在> =选择文件后,IE8,为了安全起见,这里是类似Q和记者一个在这里提出的解决方案。
Paul T. Rawkeen

1
<input type=file />数据类型是文件,我们无法通过将空字符串传递到输入字段来清除它。
Usman Mughal

在Chrome上也可以使用。看到此stackoverflow.com/a/11953476/1830909和我在下面的评论可能会很有用。
QMaster

如何使用jquery在文件输入中的多个文件上传中删除文件?
永远学习的学生


7

这也是我喜欢使用的方法,但是我相信您需要将bool true参数添加到clone方法中,以使任何事件都与新对象保持关联,并且需要清除内容。

    var input = $("#fileInput");

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

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



2

对于React用户

e.target.value = ""

但是,如果文件输入元素是由另一个元素(带有htmlFor属性)触发的-这意味着您没有该事件

因此,您可以使用ref:

在func开头:

const inputRef = React.useRef();

在输入元素上

<input type="file" ref={inputRef} />

然后在onClick函数上(例如),您可以编写

inputRef.current.value = "" 
  • 在React类中-相同的想法,但构造函数不同: this.inputRef = React.createRef()

1

如果您要确定它具有跨浏览器功能,则另一种解决方案是先删除标签,然后再执行append()或prepend(),或者以其他方式重新添加具有相同属性的输入标签的新实例。 。

<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']"));



0

在我的情况下,其他解决方案除此以外不起作用:

$('.bootstrap-filestyle :input').val('');

但是,如果页面上输入的文件不止1个,它将重置所有文件的文本。


0

获取输入id并把val设置为空,如下所示:注意:不要在val空双引号val(“”)之间放置空格。

 $('#imageFileId').val("")

0

此代码适用于所有浏览器和所有输入。

$('#your_target_input').attr('value', '');

我建议您像这样使用:$(document).ready(function( {$('#your_target_input').attr('value', ''); } );
reza laki
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.