我有以下闪亮的应用程序
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
元素已经有一个事件侦听器,上面有一个匿名函数,我无法复制。
可能有一种我不知道的更简单的方法,知道如何在 shiny 中构建有条件的上传器吗?
这
似乎有效:
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)