Home > other >  Exclude a choice from a shiny widget when this choice is selected in another shiny widget
Exclude a choice from a shiny widget when this choice is selected in another shiny widget

Time:08-12

In the shiny app below I want when a choice is selected in one of the 2 widgets then this choice to be unavailable or hidden from the other widget in a way that it will not be possible for both of them to have the same value at the same time.

library(shiny)
library(shinydashboard)
library(shinyWidgets)
choices = c("RC", "TP", "IY", "HP","Population")

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(
    pickerInput(
      inputId = "rtihcol1",
      label = "Selection for column 1", 
      choices = choices,
      selected = "Population",
      options = list(
        `actions-box` = TRUE), 
      multiple = F
      
      
    ),
    #the 6th dropdown of the 1st column
    
  
         #the dropdown from which you select between RC, TP, IY, HP
         pickerInput(
           inputId = "rtih",
           label = "Selection for column 2", 
           choices = choices,
           selected = "RC",
           options = list(
             `actions-box` = TRUE), 
           multiple = F
  )),
  dashboardBody()
)

server <- function(input, output, session) {
  observeEvent(input$rtih, {
    updateSelectInput(session, "rtihcol1", choices = choices[!choices %in% input$rtih])
  })
  
  observeEvent(input$rtihcol1, {
    updateSelectInput(session, "rtih", choices = choices[!choices %in% input$rtihcol1])
  })
}

shinyApp(ui, server)    

CodePudding user response:

One option would be to use observeEvent and updateSelectInput to dynamically set the choices for the selectInputs. Note: To make this work it's important to set the selected choice to different values when starting the app.

library(shiny)
library(shinydashboard)

choices <- c("Pop", "RC", "RT")

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(
    selectInput("Pr", "Select the price for analysis", choices = choices, multiple = F, selected = choices[1]),
    selectInput("Pr2", "Select the price for analysis", choices = choices, multiple = F, selected = choices[2])
  ),
  dashboardBody()
)

server <- function(input, output, session) {
  observeEvent(input$Pr, {
    updateSelectInput(session, "Pr2", choices = choices[!choices %in% input$Pr])
  })
  
  observeEvent(input$Pr2, {
    updateSelectInput(session, "Pr", choices = choices[!choices %in% input$Pr2])
  })
}

shinyApp(ui, server)
  • Related