清除< input type ='file'/>使用jQuery [英] Clearing <input type='file' /> using jQuery

查看:105
本文介绍了清除< input type ='file'/>使用jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用jQuery清除< input type ='file'/> 控制值?我已经尝试了以下方法:

$ $ $ $''$'$'$'$'$'$''。attr({value:''});

但是不行。

轻松:在元素周围包装一个< form> ,调用窗体上的reset,然后使用unwrap()删除窗体。不同于这个线程中的clone()解决方案,最终会得到相同的元素(包括设置的自定义属性)。



测试和工作在Opera,Firefox,Safari,Chrome和IE6 +中。也适用于其他类型的表单元素,除了 type =hidden



http://jsfiddle.net/rPaZQ/

  function resetFormElement(e){
e.wrap('< form>)。closest('form')。get(0).reset();
e.unwrap();

//防止表单提交
e.stopPropagation();
e.preventDefault();





$ b

如下Timo注意到的,如果你有按钮触发复位字段放在< form> 中,你必须调用preventDefault来防止< button> 触发一个提交。

编辑



由于一个不确定的错误,在IE 11中不起作用。文本(文件名)在输入时被清除,但是它的 File 列表仍然被填充。


Is it possible to clear an <input type='file' /> control value with jQuery? I've tried the following:

$('#control').attr({ value: '' }); 

But it's not working.

解决方案

Easy: you wrap a <form> around the element, call reset on the form, then remove the form using unwrap(). Unlike the clone() solutions otherwise in this thread, you end up with the same element at the end (including custom properties that were set on it).

Tested and working in Opera, Firefox, Safari, Chrome and IE6+. Also works on other types of form elements, with the exception of type="hidden".

http://jsfiddle.net/rPaZQ/

function resetFormElement(e) {
  e.wrap('<form>').closest('form').get(0).reset();
  e.unwrap();

  // Prevent form submission
  e.stopPropagation();
  e.preventDefault();
}

As Timo notes below, if you have the buttons to trigger the reset of the field inside of the <form>, you must call preventDefault on the event to prevent the <button> from triggering a submit.

Edit

Does not work in IE 11 due to an unfixed bug. The text (file name) is cleared on the input, but its File list remains populated.

这篇关于清除&lt; input type ='file'/&gt;使用jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆