使用jQuery清除<input type='file' />的内容

559

使用jQuery清除控件的值是否可能?我已经尝试了以下方法:

$('#control').attr({ value: '' }); 

但是它没有起作用。

27个回答

0
使其异步化,在按钮所需的动作完成后重置它。
    <!-- Html Markup --->
    <input id="btn" type="file" value="Button" onchange="function()" />

    <script>
    //Function
    function function(e) {

        //input your coding here           

        //Reset
        var controlInput = $("#btn");
        controlInput.replaceWith(controlInput = controlInput.val('').clone(true));
    } 
    </script>

0

这适用于Chrome、FF和Safari

$("#control").val("")

可能不兼容IE或Opera浏览器


1
看起来几乎与OP中所述的问题完全相同。 - Trindaz
1
不是 ECMAScript 标准,input type file 的值是受保护的属性,出于安全原因。 - e-info128

0

对我来说它不起作用:

$('#Attachment').replaceWith($(this).clone());
or 
$('#Attachment').replaceWith($('#Attachment').clone());

所以在ASP MVC中,我使用Razor功能来替换文件输入。 首先创建一个带有ID和名称的输入字符串变量,然后在页面上使用它并在重置按钮单击时进行替换:

@{
    var attachmentInput = Html.TextBoxFor(c => c.Attachment, new { type = "file" });
}

@attachmentInput

<button type="button" onclick="$('#@(Html.IdFor(p => p.Attachment))').replaceWith('@(attachmentInput)');">--</button>

0
一种简单的方法是将输入类型更改,然后再次更改回来。
类似于这样:
var input = $('#attachments');
input.prop('type', 'text');
input.prop('type', 'file')

-1

您可以这样用克隆替换它

var clone = $('#control').clone();

$('#control').replacewith(clone);

但是这个克隆也会带着它的值,所以你最好这样做。

var emtyValue = $('#control').val('');
var clone = emptyValue.clone();

$('#control').replacewith(clone);

-4

我对 Opera 毫不在意。如果你在意的话,就把它包装成表单。我个人并不在意,我会使用我的方法。 - Anonymous
2
这并不是一个好的答案,但主要问题在于态度非常恶劣。 - Isaac

-5
什么?在你的验证函数中,只需放置


document.onlyform.upload.value="";

假设上传是名称:

<input type="file" name="upload" id="csv_doc"/>

我正在使用JSP,不确定这是否有所不同...

对我来说有效,而且我认为它更容易。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接