用于重置单个文件输入值的按钮,名称为“file []”(数组)

时间:2015-12-10 20:25:46

标签: javascript jquery

我正在尝试创建一个删除按钮来清除<input type="file">的值。我遇到的问题是我不知道如何让每个按钮指向各自的<input>

我正在使用JQuery插件ezdz上传并创建图像的预览,我可以使用$ezdz预定义的var轻松地将按钮添加到每个输入中:

$ezdz.parent('div').find('div.arrow_box').html('<p><a href="#" onClick="window.resetMethod($(this.form[\'file[]\']));return false;">Quitar imagen</a></p>');
$ezdz.parent('div').find('div.arrow_box').removeClass('hide');

我需要创建一个重置文件输入的函数:

window.resetMethod = 
function (e) {
      $(this).parent('div').find('input').get(0).reset();
}

但问题出在按钮上......

<a href="#" onClick="window.resetMethod($(this.form[\'file[]\']));return false;">Quitar imagen</a>

这是html代码:

<div class="first">
    <!-- ezdz creates the following div and it'll be the container for the img -->
    <div>Drop a file</div> <!-- This div is $ezdz -->
    <input type="file" name="file[]" accept="image/jpeg" /><div class="arrow_box hide"></div>
</div>

有什么想让这个有用吗?

编辑:抱歉,我没有意识到该功能会重置整个表格。我需要重置按钮上方的输入。

我在控制台中收到以下错误:

TypeError: $(...).parent(...).find(...).get(...) is undefined

1 个答案:

答案 0 :(得分:2)

this.form[...]处理程序中的

onClick将失败。我想你的控制台会显示错误。在调用时,对应于锚元素(a),并且该元素没有 form 属性。

所以替换:

<a href="#" onClick="window.resetMethod($(this.form[\'file[]\']));return false;">Quitar imagen</a>

人:

<a href="#" onClick="window.resetMethod($(this));return false;">Quitar imagen</a>

函数resetMethod不要求您传递表单对象。只要元素以预期的形式放置,您就可以将它(作为jQuery对象)传递给函数,它将找到该表单并重置它。

resetMethod函数似乎也存在问题,因为它的包装确实存在问题。我建议跳过那部分,然后使用if,就像这样:

window.resetMethod = function (elem) {
    var frm = elem.closest('form');
    if (frm.length) {
        frm.get(0).reset();
    }
    return false; // cancel default
}

由于return false,您可以将onclick部分简化为:

<a href="#" onClick="return resetMethod($(this));">Quitar imagen</a>

您也不需要使用window前缀。

请注意,该功能还会重置您在同一表单中可能拥有的任何其他输入。

如果您只想重置文件上传输入,请使用此函数的变体:

window.resetMethod = function (elem) {
      frm = elem.closest('form');
      console.log(frm);
      if (frm.length) {
          upload = frm.find('input[type=file]');
          console.log(upload);
          if (upload.length) {
              // clear file-upload by
              // re-injecting the html for it in the dom:
              upload.replaceWith($("<p>").append(upload.clone()).html());
          }
      }
      return false; // cancel default
}