SBista
SBista

Reputation: 7704

Remove style tag added from server side

I am adding style tags based on the users input. Depending upon the radio button selected by the user the border colour of the selectInput changes. In the sample code below, I am setting the colour to red if user chooses the "Error" in radiobutton and I set it back to grey(default color) if user chooses "No Error".

The problem I am facing is that every time I renderUI with these tags the style tags keeps getting added to the html head. Ideally what I would like to do is that remove the style tag that I previously added. Is there a way to do that?

Following is the code that I am currently using:

library(shiny)

  ui <- fluidPage(

    uiOutput("Border_Arg"),

    radioButtons("RBtn", "Choices", choices = c("Error", "No Error")),

    selectInput("Select1", "Option1", choices = NULL)

  )


  server <- function(input, output){

    output$Border_Arg <- renderUI({

      if(input$RBtn == "Error"){
        tagList(
          tags$head(tags$style(HTML("#Select1 ~ .selectize-control.single .selectize-input {border: 1px solid red;}")))
          ) 
      }else if(input$RBtn == "No Error"){
        #Here, instead of setting the style to default value I would like to remove the style that was previously added
        tagList(
        tags$head(tags$style(HTML("#Select1 ~ .selectize-control.single .selectize-input {border: 1px solid #cccccc;}")))
        ) 
      }

    })
  }


  shinyApp(ui = ui, server = server)

Upvotes: 2

Views: 881

Answers (1)

GGamba
GGamba

Reputation: 13680

What you need to do is have a CSS class that add the style you want, and then add and remove the class on the element.

We can use the shinyjs package to help with that:

library(shiny)
library(shinyjs)

ui <- fluidPage(

    useShinyjs(),
    inlineCSS(list(.error = "border: 2px solid red")),

    uiOutput("Border_Arg"),

    radioButtons("RBtn", "Choices", choices = c("Error", "No Error")),

    selectInput("Select1", "Option1", choices = LETTERS[1:4])

)


server <- function(input, output){

    output$Border_Arg <- renderUI({

        if(input$RBtn == "Error"){
          addCssClass(class = 'error', selector = '#Select1 ~ .selectize-control.single .selectize-input')
        }else if(input$RBtn == "No Error"){
            removeCssClass(class = 'error', selector = '#Select1 ~ .selectize-control.single .selectize-input')
        }

    })
}


shinyApp(ui = ui, server = server)

Upvotes: 4

Related Questions