下面的应用程序包含一个带有两个选项(下载
和上传
)的selectInput input$set1
和一个单选按钮组input $set2
使用 renderUI()
渲染。我正在使用自定义消息处理程序,根据 selectInput 的值禁用单选按钮组中的单选按钮(如果 input$set1 == 'download'
则禁用 upload
code> 单选按钮,否则启用它)。
这是应用程序:
library(shiny)
library(shinyWidgets)
library(shinydashboard)
toggleRadioOpt <- function(session, inputId, choice, enable = TRUE, selected) {
session$sendCustomMessage(
type = 'toggleRadioOpt',
message = list(id = inputId, choice = choice, enable = enable, selected = selected)
)
}
modUI <- function(id) {
ns <- NS(id)
tagList(
tags$head(
tags$script("
Shiny.addCustomMessageHandler('toggleRadioOpt',
function(data) {
$('#' + data.id + ' input[value = \"' + data.choice + '\"]').attr('disabled', !data.enable).prop('checked', false);
if(data.selected !== null) {
$('#' + data.id + ' input[value = \"' + data.selected + '\"]').prop('checked', true);
}
}
);
")
),
prettyRadioButtons(ns('set1'), label = 'Select', choices = c('download', 'upload', 'abb')),
# selectInput(ns('set1'), label = 'Select', choices = c('download', 'upload', 'sql')),
uiOutput(ns('taskUI'))
)
}
modServer <- shinyServer(function(input, output, session) {
ns = session$ns
output$taskUI <- renderUI({
switch(input$set1,
'download' = selectInput(ns('data'), '', state.area),
'upload' = selectInput(ns('data'), '', state.center),
'abb' = tagList(
selectInput(ns('data'), '', state.abb),
actionButton(ns('upload'), 'Upload')
)
)
prettyRadioButtons(ns('set2'), label = '', choices = c('split', 'upload'))
})
observe({
if(!is.null(input$set2)) {
if(input$set1 %in% c('download', 'abb')) {
toggleRadioOpt(session = session, inputId = ns('set2'), choice = 'upload', enable = F, selected = 'split')
} else {
toggleRadioOpt(session = session, inputId = ns('set2'), choice = 'upload', enable = T, selected = 'split')
}
}
})
})
# UI ----------------------------------------------------------------------
ui = fluidPage(modUI('first'))
# SERVER ------------------------------------------------------------------
server <- shinyServer(function(input, output, session) {
callModule(modServer, 'first')
})
shinyApp(ui, server)
如果单选按钮组是在 UI 中创建的,则处理程序将按预期工作,但如果使用 renderUI()
创建按钮,则处理程序将失败。具体来说,它在启动时失败,但如果随后更改 input$set1
,它就会工作。我是使用自定义消息处理程序的新手,所以我不确定这里发生了什么或如何修复它。我认为这可能与 UI 加载之前触发的 jQuery 有关,但我不能确定。
最佳答案
I thought it may have something to do with the jQuery being triggered before the UI has loaded but I can't be sure.
我想是的。在 UI 加载之前,input$set2
为 NULL
。你可以这样做:
observe({
if(!is.null(input$set2)){
if(input$set1 == 'download') {
toggleRadioOpt(session = session, inputId = ns('set2'), choice = 'upload',
enable = F, selected = 'split')
} else {
toggleRadioOpt(session = session, inputId = ns('set2'), choice = 'upload',
enable = T, selected = 'split')
}
}
})
关于javascript - R Shiny - 使用自定义消息处理程序禁用单选按钮组中的单个单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55429693/