Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 765
jeromefroe Avatar asked Sep 01 '15 15:09

jeromefroe


1 Answers

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();     } }); 
like image 90
jeromefroe Avatar answered Sep 22 '22 14:09

jeromefroe