我有一个数据表,其中嵌入了selectizeInputs。我已经使用jquery在selectizeInputs中启用了一些选项(比如创建选项)。
现在,由于一个业务用例,我想禁用一些selectizeInputs (通过某些条件动态选择)。这些输入可能在2号、3号、..数据表的第n页。
但是,我只能禁用第一页上的输入,而不能禁用后续页面上的输入。我附上了一个最小的和可重复的例子,如果有人能帮我就太好了。
library(shiny)
library(DT)
ui <- fluidPage(
shinyjs::useShinyjs(),
selectizeInput(
inputId = "input",
label = "",
choices = letters[1:26],
selected = letters[1]
),
fluidRow(
DTOutput(outputId = "table"),
tags$script(HTML("Shiny.addCustomMessageHandler('unbind-DT', function(id) {
Shiny.unbindAll($('#'+id).find('table').DataTable().table().node());
})"))
)
)
df <- data.frame('a' = c(1,2), 'sel_input' = NA)
df[1,'sel_input'] <- as.character(
selectizeInput(inputId = 'mselect', choices=c('car','cars','dog'),
label=NULL, selected=NULL))
df[2,'sel_input'] <- as.character(
selectizeInput(inputId = 'nselect', choices=c('lambo','audi','merc'),
label=NULL, selected=NULL))
js <- c(
"function(){Shiny.bindAll(this.api().table().node());",
" $('#mselect').selectize({
delimiter: \',\',
persist: false,
create: function(input) {
return {
value: input,
text: input
}
}
});",
"$('#nselect').selectize({
delimiter: \',\',
persist: false,
create: function(input) {
return {
value: input,
text: input
}
}
});",
"$('#mselect')[0].selectize.enable()",
"$('#nselect')[0].selectize.disable()",
"}"
)
server <- function(input, output, session) {
observe({
print(input$mselect)
})
session$sendCustomMessage('unbind-DT', 'table')
output$table <- renderDT({
datatable(
data = df,
escape = FALSE,
options = list(
dom='tp',
pageLength=1,
processing=F,
preDrawCallback = JS('function(){Shiny.unbindAll(this.api().table().node());}'),
drawCallback = JS(js)
)
)
})
}
shinyApp(ui = ui, server = server)
发布于 2021-09-14 23:27:42
所以,我能够自己解决这个问题。基本上,这里的问题不是基于R/R的。这实际上是我忽略的代码中的一个javascript错误。
进行分页时,只有当前(选定)页面中的元素是DOM的一部分。将删除/不创建所有其他项。在上面的代码中,在drawCallback (这是每次需要重新呈现数据表时运行的代码段)中,我为所有元素发出命令,而不管它们是否存在于DOM中。因此,javascript代码会失败,禁用/启用也不会发生。
这里的解决方案是首先检查元素在DOM中是否处于活动状态,然后才发出启用/禁用命令。
因此,在本质上,将上述命令包含在if else语句中
if ($('#mselect').length > 0){
$('#mselect').selectize()[0].selectize.enable();
}
if ($('#nselect').length > 0){
$('#nselect').selectize()[0].selectize.disable();
}
这样,只有当特定元素存在于DOM中时,javascript代码才会运行,然后您就可以在分页的数据表的第二页中实现禁用selectInput。
https://stackoverflow.com/questions/69043516
复制相似问题