是否有可能清除<input type='file' />控件值与jQuery?我试过以下几种方法:
$('#control').attr({ value: '' });
但这并不奏效。
是否有可能清除<input type='file' />控件值与jQuery?我试过以下几种方法:
$('#control').attr({ value: '' });
但这并不奏效。
当前回答
这对我很有用。
$("#file").replaceWith($("#file").clone());
http://forum.jquery.com/topic/how-to-clear-a-file-input-in-ie
希望能有所帮助。
其他回答
什么? 在验证函数中
document.onlyform.upload.value="";
假设upload是名称:
<input type="file" name="upload" id="csv_doc"/>
我使用JSP,不确定这是否有区别…
对我来说是可行的,而且我觉得这样简单多了。
出于明显的安全原因,您不能设置文件输入的值,甚至是空字符串。
你所要做的就是重置字段所在的表单,或者如果你只想重置包含其他字段的表单的文件输入,使用这个:
function reset_field (e) {
e.wrap('<form>').parent('form').trigger('reset');
e.unwrap();
}
这里有一个例子:http://jsfiddle.net/v2SZJ/1/
我一直在寻找简单而干净的方法来清除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>
一个简单的方法是改变输入类型,然后再把它改回来。
就像这样:
var input = $('#attachments');
input.prop('type', 'text');
input.prop('type', 'file')
最后我得出了这个结论:
if($.browser.msie || $.browser.webkit){
// doesn't work with opera and FF
$(this).after($(this).clone(true)).remove();
}else{
this.setAttribute('type', 'text');
this.setAttribute('type', 'file');
}
也许不是最优雅的解决方案,但据我所知它很有效。