Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...