Cybernetic
Cybernetic

Reputation: 13354

How to make submit button only take value from corresponding textInput in Shiny (R)

I have a textInput field in my shiny app. I want to have a submit button (or Action button which may make more sense?) beside the textInput, so that when text is added to the textInput, the user can click on the button and the only reaction the App takes is to take in that value (not load anything else on the page) How can this be accomplished?

If I use the following code it loads everything.

shinyUI(

textInput("variable", "Add Recomendation", ""), submitButton("Add")

)

Upvotes: 3

Views: 4549

Answers (3)

Jan
Jan

Reputation: 5274

An even simpler way would be to add the submit-button directly into the rendering function. The req(input$submit) makes sure that the rendering function listens to button presses. Further we have to isolate() input$variable. Otherwise, the rendering function would not only be called when the button is pressed but also every time input$variable changes.

One difference compared to the previous solutions: while a reactive expression/value may be helpful in more complex applications, we do not need it here and can directly access the value of input$variable.

library(shiny)

ui <- basicPage(
  textInput("variable", "Add Recommendation", ""),
  actionButton("submit", "Add"),
  textOutput("text")
)

server <- function(input, output) {
  output$text = renderText({
    req(input$submit)
    return(isolate(input$variable))
  })
}

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

Upvotes: 1

jampang
jampang

Reputation: 1

library(shiny)

# Define UI for application that draws a histogram
ui <- (basicPage(
  
  textInput("variable", "Add Recommendation", ""),
  actionButton("submit", "Add"),
  textOutput("text")
  
))

# Define server logic required to draw a histogram
server <- function(input, output) {
  name <- reactive({
    return(input$variable)
  }) 
  
  observeEvent(input$submit, {
    output$text = renderText(name())
    
  })
}

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

Upvotes: 0

Eric
Eric

Reputation: 1012

I think you would need to use an actionButton() with an observer in your server. Also be sure to wrap input$variable in isolate so that it doesn't cause the observer to fire.

Something like this:

UI.R

library(shiny)    

shinyUI(basicPage(

    textInput("variable", "Add Recommendation", ""),
    actionButton("submit", "Add"),
    textOutput("text")

))

server.R

library(shiny)

shinyServer(function(input, output) {

    values <- reactiveValues(variable = NA)

    observe({

        if(input$submit > 0) {

            values$variable <- isolate(input$variable)

        }

    })

    output$text <- renderText({values$variable})

})

Upvotes: 4

Related Questions