Conditional shinydashboard box status / style

732 views Asked by At

I want to change the status / style of a shinydashboard box conditional on some inputs, basically to signal warnings to the user (see example below). Actually, I already managed to solve my problem by using shinyjs and its extendShinyjs functionality. But I would like to understand why my initial attempts --based on shinyjs's removeClass / addClass functions-- failed. So, my question is: Why does the approach in the second box in the example app below fail?

When running the app, just do enter values larger than 12 ;)

library(shiny)
library(shinydashboard)
library(shinyjs)

jscode <- "
shinyjs.warningBox = function(boxid) {
$('#' + boxid).parent().removeClass('box-success').addClass('box-warning');
};
shinyjs.successBox = function(boxid) {
$('#' + boxid).parent().removeClass('box-warning').addClass('box-success');
}
"

dbBody <- dashboardBody(
    useShinyjs(),
    extendShinyjs(text = jscode),

    box(
        id = "input-box-1",
        title = "Here it works", 
        status = "success",
        solidHeader = TRUE,

        numericInput(
            inputId = "n1", 
            label = "Do not enter anything larger than 12", 
            value = 10)
    ),

    box(
        id = "input-box-2",
        title = "Here it doesn't", 
        status = "success",
        solidHeader = TRUE,

        numericInput(
            inputId = "n2", 
            label = "Do not enter anything larger than 12", 
            value = 10)
    )
)

server <- function(input, output) {
    observe({
        if (input$n1 > 12) js$warningBox("input-box-1")
        else js$successBox("input-box-1")
    })

    observe({
        selector <- "$('#input-box-2').parent()"
        if (input$n2 > 12) {
            shinyjs::removeClass(
                selector = selector, class = "box-success")
            shinyjs::addClass(
                selector = selector, class = "box-warning")
        } else {
            shinyjs::removeClass(
                selector = selector, class = "box-warning")
            shinyjs::addClass(
                selector = selector, class = "box-success")
        }
    })
}

shinyApp(
    ui = dashboardPage(
        dashboardHeader(title = "Box styles"),
        dashboardSidebar(),
        dbBody
    ),
    server = server
)
0

There are 0 answers