简体   繁体   中英

change numericInput value based on current value when user changes another input

I'm creating a shiny app that is based in inches, but would like to allow the user to change the units to centimeters. When the user changes the units (in either direction), I would like the current value of a numericInput to change appropriately. Here is what I have come up with:

shinyApp(
  ui = fluidPage(
    numericInput("length","Length",1),
    radioButtons("units", "Units", c(Inches="inches", Centimeters="cms"))
  ),
  server = function(input,output,session) {
    observe({
      updateNumericInput(session, inputId="length", value=ifelse(input$units=="cms", input$length*2.54,input$length/2.54))
    })
  }
)

As you will see if you run the app, currently the problem with my code is that there is an infinite loop because when input$length gets changed, the observe gets called again and input$length gets updated, and the pattern repeats.

At default, input$length=1 and input$units="inches" . What I would like to occur is that if the user changes to input$units="cms" , then input$length changes to 2.54 . If the user subsequently changes back to inches, then input$length changes back to 1 . At this point, if the user changes the input$length to 2 and then changes input$units to "cms" , then input$length should be updated to 5.08 . How can I get this to work as desired?

An idea that I'm not sure how to program is to only have the observe run when input$units changes rather than when either input$units or input$length changes, but I'm certainly open to any solution.

This is a job for isolate : when you don't want that a change in an input triggers an event, you can isolate the expression containing the input. Try:

updateNumericInput(session, inputId="length", value=ifelse(input$units=="cms", isolate(input$length)*2.54,isolate(input$length)/2.54))

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