是否有可能清除<input type='file' />控件值与jQuery?我试过以下几种方法:
$('#control').attr({ value: '' });
但这并不奏效。
是否有可能清除<input type='file' />控件值与jQuery?我试过以下几种方法:
$('#control').attr({ value: '' });
但这并不奏效。
当前回答
我已经设法让这个工作使用以下…
function resetFileElement(ele)
{
ele.val('');
ele.wrap('<form>').parent('form').trigger('reset');
ele.unwrap();
ele.prop('files')[0] = null;
ele.replaceWith(ele.clone());
}
这已在IE10, FF, Chrome和Opera测试。
有两点需要注意……
在FF中仍然不能正常工作,如果您刷新页面,文件元素将使用所选文件重新填充。我不知道它是从哪里得到这些信息的。还有什么与文件输入元素相关,我可以尝试清除? 记住对附加到文件输入元素的任何事件使用委托,这样它们在克隆时仍然有效。
我不明白的是,到底是谁认为不允许您从无效的不可接受的文件选择中清除输入字段是一个好主意?
不要让我动态地设置它的值这样我就不能从用户的操作系统中窃取文件,但是我可以在不重置整个表单的情况下清除无效的选择。
它不像'accept'做任何事情,除了一个过滤器,无论如何,在IE10,它甚至不理解微软Word mime类型,这是一个笑话!
其他回答
这适用于Chrome, FF和Safari
$("#control").val("")
可能无法与IE或Opera工作
将其设置为异步的,并在完成按钮所需的操作后重置它。
<!-- 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>
我一直在寻找简单而干净的方法来清除HTML文件输入,上面的答案是伟大的,但没有一个真正回答我在寻找什么,直到我在网络上遇到了一个简单而优雅的方法来做到这一点:
var $input = $("#control");
$input.replaceWith($input.val('').clone(true));
这一切都要归功于克里斯·科伊尔。
// 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>
我的火狐40.0.3只支持这个功能
$('input[type=file]').val('');
$('input[type=file]').replaceWith($('input[type=file]').clone(true));
这很简单lol(适用于所有浏览器[除了opera]):
$('input[type=file]').each(function(){
$(this).after($(this).clone(true)).remove();
});
JS Fiddle: http://jsfiddle.net/cw84x/1/