首页 > 解决方案 > 使用 JS 在模态中选择 html 类以在上传表单中显示文件名(在 Laravel 中)

问题描述

我有以下模式:

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Upload de Anexo</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <form action="{{ route('ordem_attachment.store') }}" method="post" enctype="multipart/form-data">
          <input type="hidden" id="ordem_id" name="ordem_id" value="{{ $ordem->id }}">
          <div class="form-group">
            <label for="attachment_id">Tipo de Anexo</label>
            {{ csrf_field() }}
            <select class="form-control" name="attachment_id">
              <option disabled selected value> -- Selecione um Tipo de Anexo -- </option>
              @forelse($attachments as $att)
              <option value="{{ $att->id }}">{{ $att->descricao }}</option>
              @empty
              @endforelse
            </select>
          </div>
          <div class="custom-file">
            <input type="file" name="anexo" id="file" class="custom-file-input">
            <label class="custom-file-label" for="file">Selecionar Arquivo</label>
          </div>
          <div class="modal-footer">
            <input type="submit" value="Enviar" class="btn btn-primary" />
            <button type="button" class="btn btn-danger" data-dismiss="modal">Cancelar</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

我正在使用以下 JS 代码来尝试在选择文件时显示文件的名称:

<script>
    document.querySelector('.custom-file-input').addEventListener('change',function(e){
      var fileName = document.getElementById("file").files[0].name;
      var nextSibling = e.target.nextElementSibling
      nextSibling.innerText = fileName
    })
</script> 

但它不起作用,我不知道为什么。该文件已正常上传,但我无法在表单中显示所选文件的名称。

标签: javascriptphphtmllaravelbootstrap-modal

解决方案


代替

var fileName = document.getElementById("file").files[0].name;

你可以试试

let file=e.target.files[0];

var fileName = file['name'];

如果不起作用,您也可以尝试在 HTML 添加 onchange="fileFunction()" 中使用这样的 onchange 事件

<div class="custom-file">
        <input type="file" name="anexo" id="file" class="custom-file-input" onchange="fileFunction()">
        <label class="custom-file-label" for="file">Selecionar Arquivo</label>
    </div>

并在你的 javascript 添加

function fileFunction(e){
             
                alert(document.getElementById("file").files[0].name);
                }

上传文件后,警报将显示文件名


推荐阅读