我有以下闪亮的应用程序
require(shiny)
ui <- fluidPage(
numericInput("num", "num:", 10, min = 1, max = 100),
fileInput(inputId = "upl", multiple = T, label = "upl")
)
server <- function(input, output) {
}
shinyApp(ui, server)
我希望fileInput
上传器仅上传numericInput
中指定的文件数量的文件。否则,它应该显示一条消息,指示文件数量错误。
我尝试为此使用shinyjs
//remove existing listener
document.getElementById('upl').outerHTML = document.getElementById('upl').outerHTML;
document.getElementById('upl').addEventListener('change', function() {
if(document.getElementById('upl').files.length == document.getElementById('num').value) {
// something that uploads the files
// I tried to copy the function from the already existing listener, but its anonymous and has no reference so its impossible to copy
} else {
alert('wrong number of files');
}
})
我还没有找到一种基于条件的停止或启动上传的方法,因为input
元素已经具有一个事件监听器,该事件监听器带有一个我无法复制的匿名函数。
我可能不知道有一种更简单的方法,如何在闪亮的环境中构建条件上传器?
答案 0 :(得分:1)
这似乎可行:
library(shiny)
library(shinyjs)
js <- "
$(document).ready(function(){
document.getElementById('upl').addEventListener('change', function() {
if(document.getElementById('upl').files.length == document.getElementById('num').value) {
return true;
} else {
alert('wrong number of files');
this.value = '';
return false;
}
})
})"
ui <- fluidPage(
useShinyjs(),
tags$head(tags$script(HTML(js))),
numericInput("num", "num:", 2, min = 1, max = 100),
fileInput(inputId = "upl", multiple = T, label = "upl")
)
server <- function(input, output) { }
shinyApp(ui, server)