Last active
November 4, 2022 01:47
-
-
Save cecilialee/4362b14107b3181eeddf95ca29cecdf0 to your computer and use it in GitHub Desktop.
Modal dialog prompt for inputs in Shiny. #r #shiny
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(shiny) | |
shinyApp( | |
ui = basicPage( | |
actionButton("show", "Show modal dialog"), | |
verbatimTextOutput("print") | |
), | |
server = function(input, output) { | |
vals <- reactiveValues(txt = NULL) | |
# Create modal | |
popupModal <- function(failed = FALSE) { | |
modalDialog( | |
textInput("txt", "Write something"), | |
if (failed) | |
div(tags$b("You did not input anything", style = "color: red;")), | |
footer = tagList( | |
modalButton("Cancel"), | |
actionButton("ok", "OK") | |
) | |
) | |
} | |
# Show modal when button is clicked. | |
observeEvent(input$show, { | |
showModal(popupModal()) | |
}) | |
observeEvent(input$ok, { | |
if (!is.null(input$txt) && nzchar(input$txt)) { | |
vals$txt <- input$txt | |
removeModal() | |
} else { | |
showModal(popupModal(failed = TRUE)) | |
} | |
}) | |
# Print inputted text | |
output$print <- renderPrint({ | |
if (is.null(vals$txt)) | |
"No data selected" | |
else | |
vals$txt | |
}) | |
} | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(shiny) | |
shinyApp( | |
ui = basicPage( | |
actionButton("show", "Show modal dialog"), | |
verbatimTextOutput("print") | |
), | |
server = function(input, output) { | |
# Create object to store reactive values | |
vals <- reactiveValues( | |
txt = NULL, | |
error_msg = NULL, | |
print = FALSE | |
) | |
# Create modal | |
popupModal <- function() { | |
modalDialog( | |
textInput("txt", "Write something"), | |
textOutput("skip_error_msg"), | |
footer = tagList( | |
modalButton("Cancel"), | |
actionButton("ok", "OK") | |
) | |
) | |
} | |
# Show modal when button is clicked | |
observeEvent(input$show, { | |
vals$error_msg <- NULL | |
showModal(popupModal()) | |
}) | |
# Validate submission | |
observeEvent(input$ok, { | |
vals$txt <- input$txt | |
if (!is.null(vals$txt) && nzchar(vals$txt)) { | |
removeModal() | |
vals$print <- TRUE | |
} else { | |
vals$error_msg <- "You did not input anything." | |
} | |
}) | |
# Output error message | |
output$skip_error_msg <- renderText({ | |
vals$error_msg | |
}) | |
# Output inputted text | |
output$print <- renderPrint({ | |
if (vals$print) { | |
vals$txt | |
} else { | |
NULL | |
} | |
}) | |
} | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment