Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture shinyalert input field as variable

Tags:

r

shiny

shinyjs

I'm trying to use the relatively new shinyAlert package to see if it offers better results than the sweetalert package but I'm unable to figure out how to get this:

Myvar <-  shinyalert input text 

from this minimal example.

library(shiny)
library(shinyjs)
library(shinyalert)

ui <- fluidPage(
  shinyjs::useShinyjs(),
  useShinyalert(),
     actionButton("run", "Run", class = "btn-success")
)
server <- function(input, output, session) {
  shinyEnv <- environment()

  observeEvent(input$run, {

    shinyalert('hello', type='input')
  })
}
shinyApp(ui = ui, server = server)

My thanks for any help from you geniouses out there.

like image 243
Mark Avatar asked Jul 16 '17 13:07

Mark


2 Answers

Here is how you do it:

library(shiny)
library(shinyalert)

ui <- fluidPage(
  useShinyalert(),
  actionButton("run", "Run", class = "btn-success")
)
server <- function(input, output, session) {

  observeEvent(input$run, {
    shinyalert('hello', type='input', callbackR = mycallback)
  })

  mycallback <- function(value) {
    cat(value)
  }
}
shinyApp(ui = ui, server = server)

It's done using callbacks. You can assign the value to a reactive variable if you'd like.

I had fully documented the package last month and was about to release it, and then my computer crashed before I had a chance to push to github, and lost all progress. I haven't had a chance to work on it again. So sorry that the documentation isn't great yet, the package is still un-released so use at your own risk for now :)

(Notice that you don't need shinyjs for this)

like image 103
DeanAttali Avatar answered Nov 02 '22 12:11

DeanAttali


I have no experience with the package shinyalert, but you can achieve what you want with the widely used and well documented modal dialogs from shiny. Maybe you there is a reason for you to stick with shinyalert that I am unaware off, but if not, example code for achieving what you want with modal dialogs:

ui <- fluidPage(
  shinyjs::useShinyjs(),
  actionButton("run", "Run", class = "btn-success"),
  textOutput("output1")
)
server <- function(input, output, session) {

  dataModal <- function(failed = FALSE) {
    modalDialog(
      textInput("input1", "Enter text:",
                placeholder = 'Enter text here'
      )
    )
  }

  # Show modal when button is clicked.
  observeEvent(input$run, {
    showModal(dataModal())
  })

  output$output1 <- renderText({
    input$input1
  })
}
shinyApp(ui = ui, server = server)

Let me know if this helps!

like image 20
Florian Avatar answered Nov 02 '22 13:11

Florian