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(); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With