gpt4 book ai didi

javascript - 自定义文件输入按钮不会选择文件

转载 作者:行者123 更新时间:2023-11-30 14:26:14 27 4
gpt4 key购买 nike

我正在尝试使用 css/javascript 创建一个简单的文件选择按钮。我现在遇到的问题是,当我单击自定义按钮以激活隐藏文件输入按钮时,它被认为是空的。如何使用 simple_form 输入和普通 html 按钮激活隐藏文件输入按钮?

//story.js
$(document).ready(function () {
let realFileBtn = document.getElementById("story_story_video");
let customBtn = document.getElementById("story-file-upload-btn");
let customText = document.getElementById("story-file-upload-text");

if(customBtn){
customBtn.addEventListener("click", function () {
realFileBtn.click();
});
}


realFileBtn.addEventListener("change", function () {
if (realFileBtn.value) {
customText.innerHTML = realFileBtn.value;
} else {
customText.innerHTML = "No video selected"
}
});
});
//story.scss

//Real File Upload Button
#story_story_video {
display: none;
}

// Custom File Input Button
#story-file-upload-btn {
background-color: #bf318d;
color: #ffffff;
padding: 10px;
border-radius: 0.12em;
border: 1px solid #6a6a6a;
transition: 0.3s;
}

#story-file-upload-btn:hover {
background: #942a69;
cursor: pointer;
}

// Custom Text that shows which file you chose
.story-file-upload-text {
margin-left: 10px;
font-family: Arial, Helvetica, sans-serif;
color: #aaaaaa;
}
<!--_form.html.erb-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<button type="button" id="story-file-upload-btn">Select Video</button>
<br>
<%= f.input :story_video, class: 'form-control', label: false %>
<span id="story-file-upload-text">No video selected</span>
</div>

JavaScript 堆栈跟踪

Uncaught TypeError: Cannot read property 'addEventListener' of null
at HTMLDocument.<anonymous> (story_file_upload_btn.self-eb557f85ebb94b2e2cbd43807a4fc248af863cd160e98e593784d35dfff6daf2.js?body=1:13)
at mightThrow (jquery3.self-06c43429d1047ce3f355da574d8a9750209971b8b1b8f264f91f5518c5fcc060.js?body=1:3584)
at process (jquery3.self-06c43429d1047ce3f355da574d8a9750209971b8b1b8f264f91f5518c5fcc060.js?body=1:3652)

最佳答案

对于文件输入,你需要使用file_field :

<%= f.file_field :story_video, class: 'form-control', label: false %>

另请注意,如果您使用 form_with 而不是 form_for,则需要明确指定输入 ID,因为 form_with 不生成 ID。

关于javascript - 自定义文件输入按钮不会选择文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51905185/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com