如何在R Shiny中基于输入非空且为数值的条件禁用按钮?
修正方案
1. 问题根源
你的原有判断逻辑存在错误:as.numeric() 转换非数值内容时会返回NA,而 is.numeric(NA) 的返回值为TRUE,所以即使输入非数值内容,判断条件也会成立,导致按钮被错误启用。
另外使用shinyjs必须在UI中引入useShinyjs(),对应功能才会生效。
2. 修正后完整代码
UI端代码
library(shiny) library(shinydashboard) # 用到tabItem需要先加载该包 library(shinyjs) ui <- dashboardPage( dashboardHeader(), dashboardSidebar(), dashboardBody( useShinyjs(), # 必须添加该行才能使用shinyjs的功能 tabItem(tabName = "principal1", br(), fluidRow( column(2, textInput(inputId = "documento1", "Ingrese el numero de documento", "") ), column(2, br(), fluidRow( actionButton("consulta_gobutton1", label = "Procesar", icon = icon("clipboard-check") ) ) ) ) ) ) )
服务端代码
server <- function(input, output) { observeEvent(input$consulta_gobutton1, { documento1 <- input$documento1 ###HERE IS MY CODE### }) observe({ # 先去除输入内容前后的空白字符,避免空格干扰判断 input_trim <- trimws(input$documento1) # 校验逻辑:转换为数值后不为NA,同时满足非空+纯数值要求 toggleState("consulta_gobutton1", condition = !is.na(as.numeric(input_trim))) }) } shinyApp(ui, server)
补充说明
- 如果需要限制只能输入正整数、限定数值范围等额外规则,可以在判断条件中追加对应逻辑,比如要求数值大于0:
!is.na(as.numeric(input_trim)) & as.numeric(input_trim) > 0 - 如果希望从输入源就限制只能输入数字,可以把
textInput替换为numericInput,就不需要额外做数值校验了。
内容的提问来源于stack exchange,提问作者Andres Mora
相关产品推荐
相关产品推荐

