InspectorSands
InspectorSands

Reputation: 2929

Update radioButtons with javascript in Shiny upon keystroke

The following code should update button to opt2 every time q is pressed in the keyboard:

library(shiny)

fun <- "$(function(){ 
      $(document).keyup(function(e) {
      if (e.which == 81) {
        $('#button_2').prop('checked',true)
      }
      });
      })"

runApp(shinyApp(
  ui = fluidPage(
    tags$script(HTML(fun)),
    radioButtons("button", "A radio button", choices = list("opt1" = 1, "opt2" = 2)),
    textOutput("text")),
  server=function(input, output, session) {
    output$text <- renderText({input$button})
  }
))

The problem is that I don't know how Shiny stores the radio button internally. I'm trying to reference the second option of button as button_2, but it is clearly not working. Also, I'm not sure if the JQuery solution (proposed here) is the most appropriate one.

Upvotes: 0

Views: 330

Answers (1)

danielson
danielson

Reputation: 1029

I attached a screenshot of the HTML layout of your radio buttons. The problem with the solution linked was that it referenced buttons by ID, but you have not set IDs for your radio buttons. Below is a possible solution. enter image description here

fun <- "$(function() {
  $(document).keyup(function(e) {
    if (e.which == 81) {
      var $radioButtons = $('input:radio[name=button]');
      $radioButtons.filter('[value=2]').prop('checked', true);
    }
})
});"

Note: If you also want the displayed text value to update, you will need to add Shiny.onInputChange() call in your JavaScript. This will pass back a value labeled 'button' that has a value of 2.

fun <- "$(function() {
  $(document).keyup(function(e) {
    if (e.which == 81) {
      var $radioButtons = $('input:radio[name=button]');
      $radioButtons.filter('[value=2]').prop('checked', true);
      Shiny.onInputChange('button', 2);
    }
})
});"

and then update your server function to create an observer for changes to the radio buttons:

  server=function(input, output, session) {
    output$text <- renderText({input$button})
    observe({
      output$text <- renderText({input$button})
    })
  }

Upvotes: 1

Related Questions