使用uiOutput在闪亮的键盘上触发actionButton

时间:2019-04-17 15:53:44

标签: javascript r shiny

我喜欢在闪亮的应用程序中单击键盘上的Enter键时触发一个actionButton。当我将actionButton放在ui中时,它可以工作,但与uiOutput一起使用时,它不工作。

library(shiny)

jscode <- '
$(function() {
var $els = $("[data-proxy-click]");
$.each(
$els,
function(idx, el) {
var $el = $(el);
var $proxy = $("#" + $el.data("proxyClick"));
$el.keydown(function (e) {
if (e.keyCode == 13) {
$proxy.click();
}
});
}
);
});
'

ui <- fluidPage(
  tags$head(tags$script(HTML(jscode))),
  uiOutput("ui")
)

server <- function(input, output, session) {
  output$ui <- renderUI({
    tagList(
      tagAppendAttributes(passwordInput("user_pw", "Passwort",
                                        value = ""),
                          `data-proxy-click` = "user_login"
      ),
      actionButton("user_login", "Anmelden")
    )
  })

  observeEvent(input$user_login, {
    cat("clicked", "\n")
  })
}

shinyApp(ui, server)

1 个答案:

答案 0 :(得分:2)

这应该做:

library(shiny)

jscode <- '$(document).keyup(function(e) {
    if (e.key == "Enter") {
    $("#user_login").click();
}});'

ui <- fluidPage(
  tags$head(tags$script(HTML(jscode))),
  uiOutput("ui")
)

server <- function(input, output, session) {

  output$ui <- renderUI({
    tagList(
      tagAppendAttributes(passwordInput("user_pw", "Password",value = ""),`data-proxy-click` = "user_login"
      ),
      actionButton("user_login", "Anmelden")
    )
  })

  observeEvent(input$user_login, {
    cat("clicked", "\n")
  })
}

shinyApp(ui, server)