r-RShiny中的反应输入反应过快(不使用按钮)



如何让Shiny等待用户输入邮政编码(不使用按钮(。我面临的问题是,如果用户输入邮政编码的速度不够快,它会很快跳到错误。编辑:

  • 我在这个应用程序中有其他用户输入,但我在这个问题中简化了它。我希望所有其他输入都能立即响应,因为它们是单选按钮。我认为按下"返回"仍然可以做与按钮相同的事情,这不是我想要的。我想只对zipcode输入使用"Sys.sleep((",而不对其他输入使用。这可能吗
library(shiny)
shinyApp(ui <- fluidPage(sidebarPanel(
"",
textInput("zipcode", label = "Enter your zipcode.", value = 98125)

)) ,

server <- function(input, output, session) {
observeEvent(input$zipcode, {
#limits zipcode input to 5 numbers only
if (nchar(input$zipcode) != 5)
{
updateTextInput(session, 'zipcode', value = 98125)
showModal(
modalDialog(
title = "Error!",
"Only 5-character entries are permitted.",
easyClose = TRUE
)
)
}
if (is.na(as.numeric(input$zipcode)))
{
showModal(
modalDialog(
title = "Error!",
"Only numeric values are allowed. Please try again.",
easyClose = TRUE
)
)
}
})
})

您可以使用debounce:

这可以让你忽略一个非常"健谈;反应表达式,直到它变为空闲,当中间值不如最终值重要时,这很有用

您不需要Sys.sleep,它将等待millis毫秒才能触发反应:

library(shiny)
shinyApp(
ui <- fluidPage( 
sidebarPanel("", textInput("zipcode", label="Enter your zipcode.", value = 98125)

)  ) , 


server <- function(input, output, session) {
zipcode <- reactive(input$zipcode)
zipcode_d <- debounce(zipcode, millis = 2000)
observeEvent(zipcode_d(),{     #limits zipcode input to 5 numbers only
if(nchar(zipcode_d())!=5)
{
updateTextInput(session,'zipcode',value=98125)
showModal(modalDialog(
title = "Error!",
"Only 5-character entries are permitted.",
easyClose = TRUE
))
}
if(is.na(as.numeric(zipcode_d())))
{
showModal(modalDialog(
title = "Error!",
"Only numeric values are allowed. Please try again.",
easyClose = TRUE
))
}
}
)
})

添加JS代码,输入$keyPressed,当"返回";按键在任何位置按下。

library(shiny)
js <- '
$(document).on("keyup", function(e) {
if(e.keyCode == 13){
Shiny.onInputChange("keyPressed", Math.random());
}
});
'
shinyApp(ui <- fluidPage(tags$script(js),
sidebarPanel(
"",
textInput("zipcode", label = "Enter your zipcode.", value = 98125),
textOutput("zip")
)) ,

server <- function(input, output, session) {
observeEvent(input[["keyPressed"]], {
#limits zipcode input to 5 numbers only
if (nchar(input$zipcode) != 5)
{
updateTextInput(session, 'zipcode', value = 98125)
showModal(
modalDialog(
title = "Error!",
"Only 5-character entries are permitted.",
easyClose = TRUE
)
)
}
if (is.na(as.numeric(input$zipcode)))
{
showModal(
modalDialog(
title = "Error!",
"Only numeric values are allowed. Please try again.",
easyClose = TRUE
)
)
}
output$zip <- renderText(input$zipcode)
})
})

链接到:闪亮回应进入

最新更新