iboboboru iboboboru - 1 month ago 14
R Question

Disasble shiny sliderInput using shinyjs

I am building multiple lm() models using dplyr. I want to allow a user to change the independent variable value in a Shiny app - via shiny::sliderInput(). But only do so where "goodness of fit" say R^2 is greater than a threshold - otherwise disable the slider. I have tried to use the shinyjs::disable() function. See below, but can't get it to work. Any ideas on what I am doing wrong ?

library(shiny)
library(shinyjs)

# Define UI for application that draws a histogram
ui <- shinyUI(fluidPage(
sidebarLayout(
sidebarPanel(
sliderInput("test","Nice number",min = 1,max = 50,value = 30)
),
mainPanel(
textOutput("valueText")
)
)
))

# Define server to disable slider if value selected

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

value <- reactive(input$test)
output$valueText <- renderText(paste(value()))

#How to diasble slider?
reactive(if(value()==35){
shinyjs::disable('test')
}
)
})

# Run the application
shinyApp(ui = ui, server = server)

Answer

You have to call useShinyjs() in ui.R.

This is the code:

    library(shiny)
    library(shinyjs)

    # Define UI for application that draws a histogram
    ui <- shinyUI(
            tagList(
            useShinyjs(),
            fluidPage(
            sidebarLayout(
                    sidebarPanel(
                            sliderInput("test","Nice number",min = 1,max = 50,value = 30)
                    ),
                    mainPanel(
                            textOutput("valueText")
                    )
            )
    )

    )
    )

    # Define server to disable slider if value selected

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

            value <- reactive(input$test)
            output$valueText <- renderText(paste(value()))

            #How to diasble slider?
            observeEvent(value(), {
                    if(value()==35){
                            shinyjs::disable('test')
                    }  
            })

    })

    # Run the application 
    shinyApp(ui = ui, server = server)