我想清除我的表单中的文件输入。

我知道如何用同样的方法设置资源……但该方法不会擦除所选文件路径。

注意:我希望避免重新加载页面、重置表单或执行AJAX调用。

这可能吗?


当前回答

输入。Value = null是一个工作方法,但是如果从onclick事件调用它,它只会触发输入的change事件。

解决方案是在需要重置输入时手动调用onchange处理程序。

function reset_input(input) {
    $(input)[0].value = null;
    input_change_handler();
}
function input_change_handler() {
    // this happens when there's been a change in file selection

    if ($(input)[0].files.length) {
        // file(s) selected
    } else {
        // nothing is selected
    }
}
$(input).on('change', input_change_handler);

其他回答

有3种方法用javascript清除文件输入:

将value property设置为空或空。 适用于IE11+和其他现代浏览器。 创建一个新的文件输入元素并替换旧的输入元素。 缺点是您将失去事件侦听器和expando属性。 通过form. Reset()方法重置所有者表单。 为了避免影响同一所有者表单中的其他输入元素,我们可以创建一个新的空表单,并将文件输入元素附加到这个新表单并重置它。这种方法适用于所有浏览器。

我写了一个javascript函数。演示:http://jsbin.com/muhipoye/1/

function clearInputFile(f){
    if(f.value){
        try{
            f.value = ''; //for IE11, latest Chrome/Firefox/Opera...
        }catch(err){ }
        if(f.value){ //for IE5 ~ IE10
            var form = document.createElement('form'),
                parentNode = f.parentNode, ref = f.nextSibling;
            form.appendChild(f);
            form.reset();
            parentNode.insertBefore(f,ref);
        }
    }
}

不幸的是,上面的答案似乎没有一个涵盖所有的基础——至少在我用普通javascript进行的测试中没有。

.value = null似乎在FireFox, Chome, Opera和IE11(但不是IE8/9/10)上工作 FireFox上的. clonenode(和jQuery中的.clone())似乎复制了.value,因此使克隆毫无意义。

所以这里是我写的香草javascript函数,它可以在FireFox(27和28),Chrome (33), IE (8, 9, 10, 11), Opera(17)…这些是目前可供我测试的唯一浏览器。

function clearFileInput(ctrl) {
  try {
    ctrl.value = null;
  } catch(ex) { }
  if (ctrl.value) {
    ctrl.parentNode.replaceChild(ctrl.cloneNode(true), ctrl);
  }
}

ctrl参数是文件输入本身,因此该函数将被调用为…

clearFileInput(document.getElementById("myFileInput"));

这其实很简单。

document.querySelector('#input-field').value = '';

我改变了类型文本和返回类型文件使用setAttribute

'<input file-model="thefilePic" style="width:95%;" type="file" name="file" id="filepicture" accept="image/jpeg" />'

'var input=document.querySelector('#filepicture');'

if(input != null)
{
    input.setAttribute("type", "text");
    input.setAttribute("type", "file");
}

我一直在寻找简单而干净的方法来清除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>