javascript - 使用 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">×</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>
但它不起作用,我不知道为什么。该文件已正常上传,但我无法在表单中显示所选文件的名称。
解决方案
代替
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);
}
上传文件后,警报将显示文件名
推荐阅读
- node.js - 无法从 MongoDB 抓取数据以在 Express 上使用
- python - 如何在 Google Colab 中从 HTML 文件中提取文本
- forms - 在 Flask 中使用选择类
- reactjs - D3.csv 未从本地 csv 文件加载数据
- double - 双星计算
- python - 我无法根据三个标准用 networkx 形成图表
- php - Laravel 验证:required_if 条件总是通过
- html - Safari:使用 % 设置图像高度
- javascript - 异步变量在条件逻辑中显示为空,但它存在于控制台日志中
- javascript - 链接文本不尊重 div 边界