简体   繁体   中英

Using enter key with action button in R Shiny

I am trying to write a javascript function to extend the R shiny action button demo . I would like the user to be able to enter a number by both clicking the action button and by hitting enter when they have selected the number input form. The code for ui.R is:

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")
  )
))

and server.R:

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

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

I included the following javascript in a file called enter_button.js within the www/ folder:

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

However, when I run the app, select the number input form and hit enter the action button does not get incremented, but it does get incremented if I click it. Alternatively, I also tested just hitting enter anywhere on the document with:

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

and that worked, so my suspicion is that the jQuery cannot find the #number element. Thanks in advance!

I was able to figure this out using the jQuery is(":focus") function, the code I used was:

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

Here is my best solution. I don't really like it tbh, but at least it works.

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 = ", ")
      # })
    }
  )
)

The code from this github page worked like a charm: https://github.com/daattali/advanced-shiny/blob/master/proxy-click/app.R

source: 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)

Add below code in shiny app.

Outside Ui and Server function -

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();
        }
      });
    }
  );
});
'

inside Ui function-

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

goButton - name of actionbutton

This will work 100% enjoy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM