Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

javascript - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...