单击“X”按钮时删除placehoder输入文件名,并显示默认输入字段文本

时间:2017-03-16 09:32:21

标签: javascript jquery

当我点击enter image description here上传图标时,我可以选择附件文件,然后我将enter image description here与“X”删除附件按钮(@extend .icon-cross;在sass中)。当我点击X删除附件按钮时,我想实现返回默认输入字段文本(上传字段)而不是附加文件名(在本例中为asdf.txt)

export default function File(sandbox, hub) {

  'use strict';


  let $file = $('input.input-file-hidden');

  /**
   * onChange event handler
   * @function onChange
   * @private
   */
  function onChange() {
    let $placeholder = $('span.input-file-placeholder', $(this).closest('div.input-file'));
    $placeholder.text(
      $(this)[0].files[0].name);
    $placeholder.parent().addClass('filled');
  }


  return {
    /**
     * initialize File
     */
    init() {
      $file.on('change', onChange);
      hub.on('inputfile:init', components => {
        components.forEach(function(component) {
          $(component).find('input.input-file-hidden').on('change', onChange);
        });
      });
    }
  }
}
&.filled {
  .input-file-button .icon {
    position: relative;
    top: -4px;
    left: -2px;
    font-size: 15px;
    @extend .icon-cross;
    @include breakpoint(phone) {
      font-size: 24px;
    }
  }
}

<div class="col-xs-12 col-md-2 no-gutter-right">
  <div class="form-elements-label">Normal</div>
  <div class="input-file input-file--with-icon">
    <label class="text-hide" for="f405">Upload field<sup>*</sup></label>
    <input class="input-file-hidden" type="file" required data-max-size="10485760" data-max-size-error-text="* File size is too large">
    <input class="input-file-elem" type="text" id="f405">
    <span class="input-file-placeholder">Upload field<sup>*</sup></span>
    <span class="input-file-bg">input background</span>
    <span class="input-file-button"><span class="icon icon-download"></span></span>
    <div class="input-file-additional-info text-right">
      <span class="additional-info-text">* JPG, PNG (max 10Mb)</span>
      <span class="error-text"></span>
    </div>
  </div>
</div>

我到目前为止尝试了,在JS中添加(在点击X上使用.val(''),我将值从“文件名,asdf.txt”更改为“No file selected” 作为悬停在输入字段上的标题)但我需要将输入字段名称更改为默认输入字段文本“上传字段”:

let $remove = $('.input-file input-file--with-icon.filled .icon-download');
remove.on("click", function () {
        $placeholder.val('');
    });

2 个答案:

答案 0 :(得分:0)

您只需要重置文件输入字段的值,然后占位符应相应更新。

$('.input-file-hidden').val('');

答案 1 :(得分:0)

我找到了解决方案,就像一个魅力,@ Peter帮我部分地提出了他的建议

function onChange() {
  let $placeholder = $('span.input-file-placeholder', $(this).closest('div.input-file'));

  if ($(this)[0].files.length > 0) {
    $placeholder.text($(this)[0].files[0].name)
  }

  $placeholder.parent().addClass('filled');

  let $remove = $('.input-file.input-file--with-icon.filled .input-file-button .icon.icon-download');

  $remove.on('click', function() {
    $placeholder.html('Upload field<sup>*</sup>');
    $file.val('');
    $placeholder.parent().removeClass('filled');
  });
}