自定义文件选择框后,选中文件名不显示及显示位置设置求助
Got it, let's get that selected filename showing up right below your SAVE button. Here's how to tweak your code step by step:
Updated HTML
First, we'll add an element to hold the filename right after your submit button:
<form> <div class="custom-file-upload"> Upload <input type="file" class="hide_file" required> </div> <br><br> <button type="submit" id="save" class="btn btn-default wf-save">SAVE</button> <!-- New element to display selected filename --> <div id="file-name-display" class="file-name"></div> </form>
Adjusted CSS
Let's polish the styles to keep your custom button looking sharp and add basic styling for the filename display:
.custom-file-upload { padding: 5px 10px; background: #00ad2d; border: 1px solid #008a24; border-radius: 4px; color: white; cursor: pointer; display: inline-block; } .hide_file { position: absolute; z-index: -1; opacity: 0; } .file-name { margin-top: 10px; padding: 5px; color: #333; font-size: 0.9em; }
JavaScript to Capture and Show Filename
Finally, add a simple event listener to detect when a file is selected and update our display element:
// Grab references to the file input and display area const fileInput = document.querySelector('.hide_file'); const fileNameDisplay = document.getElementById('file-name-display'); // Listen for file selection changes fileInput.addEventListener('change', function() { if (this.files.length > 0) { // Show the selected file's name fileNameDisplay.textContent = `Selected file: ${this.files[0].name}`; } else { // Clear the display if no file is selected fileNameDisplay.textContent = ''; } });
Quick Breakdown
- The new
<div id="file-name-display">acts as a dedicated spot to show the filename after the submit button. - The CSS keeps your custom upload button functional and hides the native file input, while styling the filename area for readability.
- The JavaScript listens for when a user picks a file: it grabs the filename from
files[0].nameand updates the display. If the user clears their selection, it empties the display automatically.
This plays nicely with your existing required validation too—if no file is selected, the form won't submit, and the filename area stays empty.
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

