Using enter key with action button in R Shiny

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.


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

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)