Manos C Manos C - 1 year ago 52
R Question

Shiny R: Conditional style for textInput

I want to change the colour of some

textInput
labels, based on a selection from a
selectInput
output.

The idea is to show, what data in new based on another selection for interactive text. The text itself, I have managed (
updateTextInput
). I would like to do something similar for their label as not all
textInput
change.

So, how do I change the colour of the
Pop
textInput based on the colour indicated from the
TagColor
input, and then again, how do I reset the color to its default style?

library(shiny)

ui<-shinyUI(
fluidPage(
selectInput("TagColor", "Color of my Tag",choices=c("Red","Blue",
"Yellow","Black", "Initial"),
selected = "Red", multiple = FALSE),
textInput("Pop", "Var1", "Test")
)
)

server<-shinyServer(function(input, output) {


})


shinyApp(ui,server)

Answer Source

One way would be to use javascript to overwrite the CSS class: To change it to red, the following JS snippet would be used: document.getElementById('Pop').style.border = 'solid red"

So to use it with your input you would write:

paste0("document.getElementById('Pop').style.border = 'solid ", tolower(input$TagColor) ,"'")

To include that in your shiny app you can use the shinyjs package.

The full app:

library(shiny)
library(shinyjs)

ui<-shinyUI(
  fluidPage(
    useShinyjs(),
    selectInput("TagColor", "Color of my Tag",choices=c("Red","Blue",
                                                        "Yellow","Black", "initial"), 
                selected = "Red", multiple = FALSE),
    textInput("Pop", "Var1", "Test")
  )
)

# 

server<-shinyServer(function(input, output) {
    observe({
      color <- paste0("solid ", tolower(input$TagColor))
      if(color == "solid initial") color <- ""
      runjs(paste0("document.getElementById('Pop').style.border =
      '", color ,"'"))
    })
})

shinyApp(ui,server)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download