使用JS在modal中选择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> 

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

而不是

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

你可以试试

let file=e.target.files[0];
var fileName = file['name'];

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

<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);
}

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

最新更新