[英]How to use JS to count the number of clicks of a selectInput function?
在運行下面的代碼時,每次點擊actionButton()
都會被正確計數,並且 output 到 UI(使用反應值y )。 我正在嘗試對selectInput()
做同樣的事情(每次進行選擇時計數)(使用反應值x ),但它並不完全正確計數,因為當第一次調用應用程序時,選擇默認選擇“Cyl " 不包括在計數中(我希望如此),並且多次點擊相同的選擇不包括在計數中(我希望所有點擊都計算在內)。 一種解決方法是在selectInput()
中包含“multiple = TRUE”,但我想看看是否有 JS 解決方案,這樣我就不必像包含“multiple = TRUE”那樣更改 UI。
順便說一句,使用“multiple = TRUE”還可以糾正output$clickSelInput...
中從 (x) 減去 1 的怪異現象; 希望 JS 解決方案也能做到這一點。
代碼:
library(shiny)
ui = fluidPage(hr(),
selectInput("selInput",label=NULL,c("Cyl"="cyl","Trans"="am","Gears"="gear"),selected=NULL),
actionButton("addBtn","Add"), hr(),
textOutput("clickSelInput"),
textOutput("clickAddBtn"),
tableOutput("data")
)
server = function(input, output) {
x = reactiveVal(0)
y = reactiveVal(0)
output$data <- renderTable({mtcars[1:10, c("mpg", input$selInput), drop = FALSE]})
observeEvent(input$selInput,{x(x()+1)})
observeEvent(input$addBtn,{y(y()+1)})
output$clickSelInput <- renderText({paste('Select Input clicks =',x()-1)})
output$clickAddBtn <- renderText({paste('Add Button clicks =',y())})
}
shinyApp(ui, server)
這是一個可行的解決方案,考慮了 SamR 的建議並通過類比使用該示例。 我必須進行其他更改才能使其正常工作。 我在下面評論了 OP 的更改。
library(shiny)
library(shinyjs) # added
ui = fluidPage(hr(),
useShinyjs(), # added, this is easy to forget to add
uiOutput("selInput"),
actionButton("addBtn","Add"), hr(),
textOutput("clickSelInput"),
textOutput("clickAddBtn"),
tableOutput("data")
)
server = function(input, output) {
x = reactiveVal(0)
y = reactiveVal(0)
output$data <- renderTable({mtcars[1:10, c("mpg", input$selInput), drop = FALSE]})
observeEvent(input$addBtn,{y(y()+1)})
# moved select input into renderUI so it can interact with JS in the observe further down:
output$selInput <- renderUI(
selectInput("selInput",label=NULL,c("Cyl"="cyl","Trans"="am","Gears"="gear"),selected=NULL)
)
output$clickSelInput <- renderText({paste('Select Input clicks =',input$rnd)}) # changed
output$clickAddBtn <- renderText({paste('Add Button clicks =',y())})
# added js:
observe({
if(is.null(input$rnd)){
runjs("
var click = 0;
Shiny.onInputChange('rnd', click)
var selInput = document.getElementById('selInput')
selInput.onclick = function() {click += 1; Shiny.onInputChange('rnd', click)};
")
}
})
}
shinyApp(ui, server)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.