poiuytrez
poiuytrez

Reputation: 22518

Select input to fill textbox in Shiny

My goal is to fill a value from a select input to a text input. The text input should be able to be modified by the user later. Unfortunately, my app does not work (the select is not filled) but there are no error.

ui.R

library(shiny)

shinyUI(fluidPage(

    sidebarLayout(
        sidebarPanel(
            selectInput("id", 
                        label = "Choose a number",
                        choices = list()
            ),

            textInput("txt1", "number", 0)

        ),



        mainPanel(

        )
    )
))

server.R

df <- data.frame(a=c(1,2),b=c(3,4))

shinyServer(function(input, output, session) {
    # fill the select input
    updateSelectInput(session, "id", choices = df$a)

    observe({
        # When I comment this line, the select is correctly filled
        updateTextInput(session, "txt1", value = df[df$a==input$id,'a'])
    })

})

Any ideas of what could be wrong?

Upvotes: 4

Views: 2603

Answers (1)

ddiez
ddiez

Reputation: 1127

Your code does not work for me for your example dataset, but it works for:

df <- data.frame(a=c("a","b"),b=c(3,4))

My guess is that updateSelectInput() requires a character. However, this does not work:

updateSelectInput(session, "id", choices = as.character(df$a))

But if you define df as:

df <- data.frame(a=c("1","2"),b=c(3,4))

This works. The complete code for the example:

library(shiny)

df <- data.frame(a=c("1","2"),b=c(3,4))

shinyApp(
  ui = shinyUI(fluidPage(
    sidebarLayout(
      sidebarPanel(
        selectInput("id", 
          label = "Choose a number",
          choices = list()
        ),
        textInput("txt1", "number", 0)
      ),
      mainPanel()
    )
  )),
  server = shinyServer(function(input, output, session) {
    updateSelectInput(session, "id", choices = df$a)

    observe({
      updateTextInput(session, "txt1", value = df[df$a==input$id,'a'])
    })
  })
)

Upvotes: 3

Related Questions