首页 > 解决方案 > Show total number of boxes checked NEXT to ActionButton

问题描述

I have a column of checkboxes. I would like to add the running total of the number of boxes checked and have it displayed next to (not beneath) the action button. Something like:

Options checked: <num_states_checked> (Max = 10)

How do I do this?

library(shiny)
library(tidyverse)

df <- tibble(
  state = c("Alabama", "Alaska", "Arizona", "Arkansas",
            "California", "Colorado", "Connecticut", "Delaware", "Florida"),
  abr = c("AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL")
)

selected_states <- c("AL", "AK","DE")

ui <- fluidPage(
  
  wellPanel(
    tags$label("Choose :"),
    fluidRow(
      column(
        width = 4,
        checkboxGroupInput(
          selected = df$abr[1:3],
          inputId = "checka",
          label = NULL,
          choiceNames = df$state,
          choiceValues = df$abr
          #choices = df$state
        ),
        actionButton("update", "Update", class = "btn-primary", width = 250, 
                     style="color: #FFF; background-color: #525252;"),
        # textOutput("selected"),
        hr()
      ),
      
    )
  )
)

server <- function(input, output, session) {
  observeEvent(input$all_none,{
    updateCheckboxGroupInput(
      session, 'checka', choiceNames = df$state, choiceValues = df$abr,
      selected = if (input$all_none == TRUE) df$state
    ) 

  }, ignoreInit = 1)
  
  output$selected <- renderText({
    all_selected <- paste(c(input$checka), collapse = ", ")
  })
}

shinyApp(ui, server)

标签: rshiny

解决方案


您可以尝试使用 splitLayout。

library(shiny)
library(tidyverse)

df <- tibble(
  state = c("Alabama", "Alaska", "Arizona", "Arkansas",
            "California", "Colorado", "Connecticut", "Delaware", "Florida"),
  abr = c("AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL")
)

selected_states <- c("AL", "AK","DE")

ui <- fluidPage(
  
  wellPanel(
    tags$label("Choose :"),
    fluidRow(
      column(
        width = 4,
        checkboxGroupInput(
          selected = df$abr[1:3],
          inputId = "checka",
          label = NULL,
          choiceNames = df$state,
          choiceValues = df$abr
          #choices = df$state
        )
      ),
      
    ),
    splitLayout(cellWidths = c(250,"50%"),
                actionButton("update", "Update", class = "btn-primary", width = 250, 
                             style="color: #FFF; background-color: #525252;"),
                h4(textOutput("selected"))
    ),
    hr()
  )
)

server <- function(input, output, session) {
  observeEvent(input$all_none,{
    updateCheckboxGroupInput(
      session, 'checka', choiceNames = df$state, choiceValues = df$abr,
      selected = if (input$all_none == TRUE) df$state
    ) 
    
  }, ignoreInit = 1)
  
  output$selected <- renderText({
    all_selected <- paste0("Options checked:", length(c(input$checka)), " (Max = ", length(df$state) , ")")
  })
}

shinyApp(ui, se

rver)


推荐阅读