简体   繁体   中英

How to populate variables after clicking an action button?

I'm trying to build a simple roller where one can click a button and populate a series of variables. I'm sure this is an easy solution, but I'm just having a hard time getting it to work.

This is what I've got. I have the interface set up just as I want it, but basically I want to get a new value for the strength row.

library(shiny)
ui = fluidPage(    
  titlePanel(""),
  sidebarLayout(      
    sidebarPanel(
      textInput("char_name","Name"),
      textInput("char_sex","Sex"),
      actionButton("rollButton", "Roll!", width = "100%"),
      hr(),
      helpText("Please consult _ if you need assitance.")
    ),
    mainPanel(
      htmlOutput("name"),
      htmlOutput("sex"),
      htmlOutput("natl"),
      htmlOutput("strength")
    )
  )
)

server = function(input, output) {
  observe({
    if(input$rollButton > 0) {
      strength <- sum(sample(1:6,3,replace=TRUE))
    }
  })
  output$name <- renderText({
    input$rollButton
    isolate(paste0('<b>Name</b>: ', input$char_name))
  })
  output$sex <- renderText({
    input$rollButton
    isolate(paste0('<b>Sex</b>: ', input$char_sex))
  })
  output$strength <- renderText({
    input$rollButton
    isolate(paste0('<b>Strength</b>: ', strength))
  })
}
shinyApp(ui = ui, server = server)

You can't read the strength variable because it was set in another function. You can create a vector of shared reactive values

server = function(input, output) {

  val <- reactiveValues(strength=NULL)

  observe({
    if(input$rollButton > 0) {
      val$strength <- sum(sample(1:6,3,replace=TRUE))
    }
  })
  output$name <- renderText({
    input$rollButton
    isolate(paste0('<b>Name</b>: ', input$char_name))
  })
  output$sex <- renderText({
    input$rollButton
    isolate(paste0('<b>Sex</b>: ', input$char_sex))
  })
  output$strength <- renderText({
    input$rollButton
    isolate(paste0('<b>Strength</b>: ', val$strength))
  })
}
shinyApp(ui = ui, server = server)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM