我正在编写代码来启动一个 js 弹出窗口,该弹出窗口将要求用户在通过使用 Rails form_for
覆盖数据来进行特定的破坏性操作之前进行确认。我已经让 js 弹出窗口和其他一些逻辑正常工作,我剩下的最后一个任务是,如果文件已附加到表单上的特定 file_field
中,我只希望激活此 js 弹出窗口。 如果该 file_field
上没有附加文件,我不需要弹出此内容。
如何获取当前是否有附加文件/文件名的状态?这是我当前的相关代码。语法很 slim :
表单 View :相关 file_field 部分
tr
= f.fields_for :location_csv, LocationCSV.new do |p|
td = p.label :attachment, "#{@campaign.form_attributes[:location_csv][:label]}"
td.csv-example
- if @campaign.has_entrants_with_locations?
p.alert Warning: Updating Will Delete Location Information For Past Completed Entries
= p.file_field :attachment, accept: "text/csv", class: 'form-control'
表单 View :提交按钮部分,包括一些其他逻辑
tr
td colspan='2'= f.submit class: "button success", id: "btn-form-submit", onclick: "destructionWarning(#{@campaign.has_entrants_with_locations?})"
Javascript 代码段
function destructionWarning(status) {
if (status === true) {
if (confirm("WARNING: This update will delete the store location data for #{@campaign.entrants_with_locations_count} campaign entrant#{'s' if @campaign.entrants_with_locations_count > 1}! Cancel to abort.") == true) {}
else {
event.preventDefault();
}
}
}
编辑:这是我更新的 JavaScript 代码段:
var csvElement = document.getElementById("quiz_campaign_location_csv_attributes_attachment");
var csvAttachment = csvElement.value;
function destructionWarning(status) {
if (status === true && csvAttachment != "") {
if (confirm("WARNING: This update will delete the store location data for #{@campaign.entrants_with_locations_count} campaign entrant#{'s' if @campaign.entrants_with_locations_count > 1}! Cancel to abort.") == true) {}
else {
event.preventDefault();
}
}
}
最佳答案
文件字段输入元素的 HTML id 是什么?您应该能够测试空字符串的输入值。
假设文件输入元素 id 的 id 是 attachment
。
使用纯 JavaScript:
var file_input = document.getElementById("attachment");
var filename = file_input.value;
if( filename != "" ) {
// There is a file specified
} else {
// There is no file specified
}
使用 jQuery:
if( $('#attachment').val() != "" ) {
// There is a file specified
} else {
// There is no file specified
}
如果您想测试 destructionWarning
函数中是否存在文件名:
function destructionWarning(server_status) {
if (server_status == true) {
var file_input = document.getElementById("attachment");
var filename = file_input.value;
if( filename != "" ) { // user has attached a file
var user_confirmed = confirm("WARNING: This update will delete the store location data for #{@campaign.entrants_with_locations_count} campaign entrant#{'s' if @campaign.entrants_with_locations_count > 1}! Cancel to abort.");
if ( user_confirmed != true) {
// cancel the form submission
event.preventDefault();
}
}
}
}
关于javascript - 在提交之前使用 javascript 获取 Rails form_for file_field 中所选文件的文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39023229/