使用jQuery清除控件的值是否可能?我已经尝试了以下方法:
$('#control').attr({ value: '' });
但是它没有起作用。
使用jQuery清除控件的值是否可能?我已经尝试了以下方法:
$('#control').attr({ value: '' });
但是它没有起作用。
我一直在寻找一种简单干净的方式来清除HTML文件输入,上面的答案都很棒,但是没有一个真正回答了我要找的东西,直到我在网上发现了一种简单而优雅的方法来做到这一点:
var $input = $("#control");
$input.replaceWith($input.val('').clone(true));
所有功劳归功于Chris Coyier。
// 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 = $("#control");
input.replaceWith(input.val('').clone(true));
出于安全考虑,文件输入的值是只读的。您无法通过编程方式将其清空(除了调用表单的reset()方法,该方法的范围不仅限于该字段)。
.clone()
方法在Opera(和其他可能的浏览器)中不起作用。它保留了内容。
对我来说,最接近的方法是Jonathan早期提供的,但在我的情况下,确保字段保留其名称、类等,会使代码变得混乱。
像Quentin所说的,这样做可能很好:
function clearInput($source) {
var $form = $('<form>')
var $targ = $source.clone().appendTo($form)
$form[0].reset()
$source.replaceWith($targ)
}
我已经成功地使用以下方法使它工作...
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中正常工作,文件元素将重新填充所选文件。我不知道它从哪里获取此信息。我可能需要尝试清除与文件输入元素相关的其他内容?
记得对文件输入元素附加的任何事件使用委派,这样在克隆时它们仍然起作用。
我不明白的是,到底是谁认为不允许您清除无效不可接受的文件选择的输入字段是一个好主意?
好吧,不要让我使用值动态设置它,这样我就无法从用户的操作系统中获取文件,但是让我清除无效的选择而不重置整个表单。
毕竟,“接受”除了过滤器外什么也做不了,在IE10中,它甚至不理解MS Word的mime类型,这真是一个笑话!
.pop()
而不是将其设置为null,这似乎可以正确清除文件。 - kmacdonald在我的Firefox 40.0.3上,只有这个才能工作
$('input[type=file]').val('');
$('input[type=file]').replaceWith($('input[type=file]').clone(true));
在任何浏览器中都能够正常工作。
var input = $(this);
var next = this.nextSibling;
var parent = input.parent();
var form = $("<form></form>");
form.append(input);
form[0].reset();
if (next) {
$(next).before(input);
} else {
parent.append(input);
}
<input type="file" id="fileID" class="aClass" name="aName"/>
var $fileInput=$("#fileID");
var $fileCopy=$("<input type='file' class='"+$fileInput.attr("class")+" id='fileID' name='"+$fileInput.attr("name")+"'/>");
$fileInput.replaceWith($fileCopy);
function clear() {
var input = document.createElement("input");
input.setAttribute('type', 'file');
input.setAttribute('value', '');
input.setAttribute('id', 'email_attach');
$('#email_attach').replaceWith( input.cloneNode() );
}
$("input[type=file]").wrap("<div id='fileWrapper'/>");
$("#fileWrapper").append("<div id='duplicateFile' style='display:none'>"+$("#fileWrapper").html()+"</div>");
$("#fileWrapper").html($("#duplicateFile").html());