C. Crt
C. Crt

Reputation: 355

How to add an input to a radiobutton selection in Shiny?

I am pretty new to Shiny and for the app I am building, I need to add an input to a radioButton selection.

This is the code for my radioButton:

values <- c("Carbs" = "carbs", "Proteins" = "prots", "BMI" = "bmi"),
radioButtons("plotVal", "What value do you want to plot?", choices = values)

I would like to add an input field. If the user doesn't find the right choice, he could enter his own value. The end result would be something like that:

What value do you want to plot?

O Carbs

O Proteins

O BMI

O [Other... ]

The [Other... ] choice would be a textInput.

I've searched the web and read all the tutorials for inputs that I found but I didn't find this specific case of figure. Can anyone help me out? Thank you.

Upvotes: 2

Views: 670

Answers (1)

ismirsehregal
ismirsehregal

Reputation: 33540

You could use updateRadioButtons:

library(shiny)

values <- c("Carbs" = "carbs", "Proteins" = "prots", "BMI" = "bmi")

ui <- fluidPage(
  radioButtons("plotVal", "What value do you want to plot?", choices = values),
  textInput("other", "Type in additional category"),
  actionButton("add", "Add category")
)

server <- function(input, output, session) {
  observeEvent(input$add, {
    req(input$other)
    otherVal <- "other"
    names(otherVal) <- input$other
    updatedValues <- c(values, otherVal)
    updateRadioButtons(session, "plotVal", choices = updatedValues)
    })
}

shinyApp(ui = ui, server = server)

Upvotes: 1

Related Questions