当用户选择另一个选项时,我想重置文件上传域。
这可以通过JavaScript实现吗?我怀疑文件上传元素的处理方式不同,因为它与用户的文件系统交互,而且可能是不可变的。
基本上,我想要的是类似(伪代码)的东西:
// Choose selecting existing file
$('#select-file').bind('focus', function() {
// Clear any files currently selected in #upload-file
$('#upload-file').val('');
}) ;
// Choose uploading new one - this works ok
$('#upload-file').bind('focus', function() {
// Clear any files currently selected in #select-file
$('#select-file').val('');
}) ;
注意:此问题及其答案的时间跨度为2009年至今。在此期间,浏览器和方法发生了变化,请考虑到这一点来选择您的解决方案:)
发布于 2009-05-07 03:09:32
您不能在大多数浏览器中设置输入值,但您可以做的是创建一个新元素,复制旧元素的属性,然后交换这两个元素。
给出一个类似这样的表单:
<form>
<input id="fileInput" name="fileInput" type="file" />
</form>
直接的DOM方式:
function clearFileInput(id)
{
var oldInput = document.getElementById(id);
var newInput = document.createElement("input");
newInput.type = "file";
newInput.id = oldInput.id;
newInput.name = oldInput.name;
newInput.className = oldInput.className;
newInput.style.cssText = oldInput.style.cssText;
// TODO: copy any other relevant attributes
oldInput.parentNode.replaceChild(newInput, oldInput);
}
clearFileInput("fileInput");
简单的DOM方式。这可能在不喜欢文件输入的旧浏览器中不起作用:
oldInput.parentNode.replaceChild(oldInput.cloneNode(), oldInput);
jQuery方式:
$("#fileInput").replaceWith($("#fileInput").val('').clone(true));
// .val('') required for FF compatibility as per @nmit026
通过jQuery:https://stackoverflow.com/a/13351234/1091947重置整个表单
发布于 2014-02-04 16:19:35
简单地说,在2014年,具有id的输入元素支持函数val('')
。
对于输入-
<input type="file" multiple="true" id="File1" name="choose-file" />
这个js清除了input元素-
$("#File1").val('');
发布于 2015-12-30 20:17:18
简单的解决方案:
document.getElementById("upload-files").value = "";
https://stackoverflow.com/questions/829571
复制相似问题