在 R Shiny 中使用 Enter 键和操作按钮

问题描述 投票:0回答:5

我正在尝试编写一个 JavaScript 函数来扩展 R 闪亮的操作按钮演示。我希望用户能够通过单击操作按钮并在选择数字输入表单时按 Enter 键来输入数字。 ui.R 的代码是:

shinyUI(pageWithSidebar(
  headerPanel("actionButton test"),
  sidebarPanel(
    tags$head(tags$script(src = "enter_button.js")), 
    numericInput("number", "N:", min = 0, max = 100, value = 50),
    br(),
    actionButton("goButton", "Go!"),
    p("Click the button to update the value displayed in the main panel.")
  ),
  mainPanel(
    verbatimTextOutput("nText")
  )
))

和服务器。R:

shinyServer(function(input, output) {
 ntext <- eventReactive(input$goButton, {
    input$number
  })

  output$nText <- renderText({
    paste(ntext(), input$goButton)
  })
})

我将以下 JavaScript 包含在 www/ 文件夹中名为 Enter_button.js 的文件中:

$("#number").keyup(function(event){
    if(event.keyCode == 13){
        $("#goButton").click();
    }
});

但是,当我运行应用程序时,选择数字输入表单并按 Enter 键,操作按钮不会增加,但如果单击它,它会增加。或者,我还测试了只需在文档中的任意位置按 Enter 键即可:

$(document).keyup(function(event){
    if(event.keyCode == 13){
        $("#goButton").click();
    }
});

这有效,所以我怀疑 jQuery 找不到 #number 元素。预先感谢!

javascript r shiny
5个回答
37
投票

我能够使用 jQuery

is(":focus")
函数解决这个问题,我使用的代码是:

$(document).keyup(function(event) {
    if ($("#number").is(":focus") && (event.key == "Enter")) {
        $("#goButton").click();
    }
});

2
投票

这个 github 页面的代码非常有用: https://github.com/daattali/advanced-shiny/blob/master/proxy-click/app.R

来源:https://deanattali.com/blog/advanced-shiny-tips/#proxy-click

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))),
  actionButton("btn", "Click me to print the value in the text field"),
  div("Or press Enter when the text field is focused to \"press\" the button"),
  tagAppendAttributes(
    textInput("text", NULL, "foo"),
    `data-proxy-click` = "btn"
  )
)

server <- function(input, output, session) {
  observeEvent(input$btn, {
    cat(input$text, "\n")
  })
}

shinyApp(ui, server)

2
投票

在闪亮的应用程序中添加以下代码。

外部Ui和服务器功能-

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 内部功能-

tags$head(tags$script(HTML(jscode))),
`data-proxy-click` = "goButton"

goButton - 操作按钮的名称

这将让你百分百享受。


0
投票

这是我最好的解决方案。老实说我不太喜欢它,但至少它有效。

library(shiny)
# This is a demo app to test a key binding on an actionButton
# Uncommenting the info item (on both UI and server) will display internal stuff
runApp( 
  list(
    #############################################
    # UI 
    #############################################
    ui = bootstrapPage(
      textInput ("myinput", label = "Write something here"),
      tags$script('
        $(document).on("keydown", function (e) {
        Shiny.onInputChange("lastkeypresscode", e.keyCode);
        });
        '),
      actionButton("GO", "Lancer le matching !"),
      # verbatimTextOutput("info"),
      verbatimTextOutput("results")
    ), 

    #############################################
    # SERVER 
    #############################################
    server = function(input, output, session) {

      # There are state variables for the input text and GO button
      curr.val <- "" # Corresponds to the current displayed input$myinput
      curr.go  <- 0  # Corresponds to the last known GO value (integer)

      lastEvent <- reactive({
        # Is reactive to the following events
        input$GO
        input$lastkeypresscode

        # Decide which action should be taken
        if(input$GO > curr.go) {
          # The user pushed the GO actionButton, so take action
          action <- 1
          curr.go <<- input$GO
        } else if(input$lastkeypresscode == 13) {
          # The user pressed the Enter key, so take action
          action <- 1
        } else {
          # The user did anything else, so do nothing
          action <- 0
        }

        return(action)
      })

      output$results = renderPrint({
        if(lastEvent() == 1) {
          curr.val <<- isolate(input$myinput)
        }
        curr.val
      })

      # output$info = renderText({
      #   paste(curr.val, curr.go, input$lastkeypresscode, sep = ", ")
      # })
    }
  )
)

0
投票

这是一个常见的用例,对于所有这些 R 开发人员来说,必须编写自己的 Javascript 事件很奇怪。

有人知道有任何 Shiny 包提供了已经封装在 R 函数中的这种行为吗?

© www.soinside.com 2019 - 2024. All rights reserved.