Shiny: How to detect which accordion elements is selected?

人盡茶涼 提交于 2020-08-20 10:36:35

问题


I have an R Shiny where server.R outputs a large number of dynamically generated UI objects.

Rather than process hundreds of objects in input to process, I thought I could use bs_accordion() from the bsplus package.

I expected bs_accordion() to report the state of the elements it controls back to server.R via the input object.

My plan had been to dynamically generate the UI elements for just the currently selected item using renderUI().

Unfortunately as far as I can tell, nothing in the bsplus package puts anything into input.

The following works in the browser console (let's suppose the accordion element is MYACCORDION)...

MYACCORDION.onclick=function(){
Shiny.onInputChange('SELECTED_DIV',document.getElementsByClassName('in')[0].getElementsByClassName('shiny-input-container')[0].id
}

... in apparently is the class bs gives the element currently selected in the accordion and there is always just one. So after I do that, input$SELECTED_DIV gets updated whenever something new is selected.

But I cannot do the above programmatically. I tried putting it in tags$script(...) at the end of fluidPage(), and it does not get attached to the div. I also tried inserting it inline via div(...,onclick=FOO) but the value of onclick gets escaped and in the output and not interpreted as text.

  • Where is the correct place to insert onclick functions in ui.R?
  • Alternatively, how do I force the value of an onclick attribute to be treated as-is without escaping symbols?
  • Or is there already a package for Shiny for attaching Javascript functions to onclick events?

Thanks.


回答1:


I'd suggest setting a dummy input that will hold the current value (or in this case, text) of the selected tab.

This might help you:

library(shiny)
library(bsplus)

shinyApp(
  ui = fluidPage(
    tags$script("$(function() {
                  $('#meet_the_beatles a').on('click', function(x) {
                    Shiny.onInputChange('selected_tab', x.target.innerText)
                  });
                });"),

    fluidRow(
      column(
        width = 6,
        offset = 3,
        bs_accordion(id = "meet_the_beatles") %>%
          bs_append(title = "John", content = "Rhythm guitar, vocals") %>%
          bs_append(title = "Paul", content = "Bass guitar, vocals") %>%
          bs_append(title = "George", content = "Lead guitar, vocals") %>%
          bs_append(title = "Ringo", content = "Drums, vocals")
      )
    ),

    HTML("<input id='selected_tab' type='text' style='display: none;'")
  ),

  server = function(input, output, session) {
    observe({
      print(paste("The selected tab is", input$selected_tab))
    })
  }
)


来源:https://stackoverflow.com/questions/53642157/shiny-how-to-detect-which-accordion-elements-is-selected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!