有条件的shinydashboard框状态/样式

时间:2016-12-21 10:11:54

标签: r shiny shinydashboard shinyjs

我想根据某些输入更改shinydashboard框的状态/样式,基本上是向用户发出警告信号(参见下面的示例)。实际上,我已经设法通过使用shinyjs及其extendShinyjs功能来解决我的问题。但我想理解为什么我最初的尝试 - 基于shinyjs的removeClass / addClass函数 - 失败了。 所以,我的问题是:为什么下面示例应用程序的第二个框中的方法失败?

运行应用时,只需执行输入大于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 个答案:

没有答案