jeromefroe jeromefroe - 1 year ago 253
R Question

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:

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

and server.R:

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

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

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

if(event.keyCode == 13){

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:

if(event.keyCode == 13){

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

Answer Source

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.keyCode == 13)) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download