3

Consider the following numeric widget in an R Shiny app:

numericInput("val", "Enter value:", value = 50, min = 0, step = 5)

If you click on the up/down arrows in the widget when the app is run, the value will increase or decrease by 5 (0, 5, 10, 15,...) as expected.

Now consider changing the min value to 1:

numericInput("val", "Enter value:", value = 50, min = 1, step = 5)

If you now click on the up/down arrows, the value will still increase/decrease by 5, but start from 1, creating the sequence 1, 6, 11, 16,...

Is it possible to maintain increments/decrements of 5 but starting from 0 (so the sequence is 0, 5, 10, 15,...) when the min value is 1?

An example where this might be needed (as in my case) is where you wish to have the user enter a (strictly) positive number, but have an increment/decrement value of 5 since multiples of 5 are nice, easy, rounded numbers (as opposed to 1, 6, 11, 16,... etc.)

qanda
  • 225
  • 3
  • 12

1 Answers1

1

You can use updateNumericInput to prevent null value in your numericInput. Here is an example:

library(shiny)

ui <- fluidPage(
  sidebarPanel(
    numericInput("val", "Enter value:", value=50, min = 0, step = 5)
  )
)

server <- function(input, output, session) {
  observeEvent(input$val, {
    x <- input$val
    if (x == 0 | is.na(x)){
      updateNumericInput(session, "val", value = 1)
    }
  })
}

shinyApp(ui, server)
DJack
  • 4,850
  • 3
  • 21
  • 45
  • Thanks for the idea. Unfortunately this won't do; I want the user to still be able to enter any real number above zero (no maximum), where the values are typically 100k, 200k, 300k (that is, house prices), so skipping by lots of tens of thousands is helpful, yet this should not prevent them from still being able to enter more precise figures. – qanda May 13 '18 at 07:43
  • That's clever. Thanks, it worked. Looks like this is also a means of providing input validation; update the 'if' conditions with whatever rules you like I imagine? – qanda May 13 '18 at 09:44
  • Yes. You could, for instance, use the modulo `x %% 5 != 0` to ensure you only have only multiples of five. – DJack May 13 '18 at 09:49
  • Cool. Not to spoil your good answer, but the solution is a little glitchy: if you click the arrows rapidly enough and do some random fast clicking etc., you can get a value of zero. Not complaining though, as the typical user wouldn't try and break it like a developer! Thanks again. – qanda May 13 '18 at 09:59
  • Yes, it is a workaround. It might be a better solution. – DJack May 13 '18 at 10:02