How to force shiny input to be capitalized

Viewed 392

I have found a few javascript functions that transform input text into capitalized text (here and here). But I am unsure how to apply the javascript function to shiny inputs. See below I've included an example selectizeInput function.

ui <- fluidPage(theme = "bootstrap.css",
                
                fluidRow(
                    column(6,
                           selectizeInput("input", "Input words here", 
                                          choices = NULL, 
                                          multiple = TRUE, 
                                          options = list(create = TRUE)),
                           column(6,
                                  textOutput("test"))
)
    )
        )

server <- function(input, output) {
    
output$test<-renderText({input$input})
    
}
2 Answers

One approach would be to observe the change in the input and update it with the capitalized value:

library(shiny)

ui <-
    fluidPage(theme = "bootstrap.css",
              fluidRow(
                column(6,
                       selectizeInput("input", "Input words here", 
                                      choices = NULL, 
                                      multiple = TRUE, 
                                      options = list(create = TRUE)),
                       column(6,textOutput("test"))
                    ))
)

server <- function(input, output, session) {
  observeEvent(input$input,{
    updateSelectizeInput(session, "input",
                         choices = tools::toTitleCase(input$input),
                         selected = tools::toTitleCase(input$input))
    })
    
    output$test<-renderText({input$input})
}

shinyApp(ui = ui, server = server)

image

Instead of TRUE, you can use a JavaScript function for the create option, which processes the input:

createOption <- "
function(input, callback) {
  var item = input.toUpperCase();
  callback({value: item, label: item});
}
"

ui <- fluidPage(
  theme = "bootstrap.css",
  
  fluidRow(
    column(6,
           selectizeInput(
             "input", "Input words here", 
             choices = NULL, 
             multiple = TRUE, 
             options = list(
               create = I(createOption)
             )
           )
    ),
    column(6,
           textOutput("test")
    )
  )
)
Related