Search code examples
rshinyshiny-server

How to display age automatically when date of birth is entered in R shiny?


How to display age automatically when date of birth is entered in R shiny? UI.R

shinyUI(
    fuildpage({
    column(2, actionButton("calculate", "Calculate age")),
    fluidRow(uiOutput("calculatedage")
})

SERVER.R

library(shiny)
library(shinyjs)
library(shinythemes)

shinyServer(function(input, output,session){

    observeEvent( input$calculate, 
       output$calculatedage <- renderUI({isolate({

      fluidRow(
          column(3,dateInput("dob", label="DATE OF BIRTH:",min = "1960-01-01",
          max = Sys.Date(), format = "yyyy-mm-dd", startview = "year",
          weekstart = 0, language = "en")),

          column(3, textInput("age",label = "AGE:")),
         column(3,textInput("address",label = "Address:"))                                              
          )

  })}))           
})

In the above code there is a button called calculate age when that is clicked the user can enter the dob.When the user enters the dob the age should be displayed automatically in the textbox defined "age". How can this be done in R shiny


Solution

  • How about this?

    library(shiny)
    library(shinyjs)
    library(shinythemes)
    
    ui <- shinyUI(
      fluidPage({
        column(2, actionButton("calculate", "Calculate age"),
        fluidRow(uiOutput("calculatedage")))
      })
    )
    
    server <- shinyServer(function(input, output,session){
    
          observeEvent( input$calculate, 
                        output$calculatedage <- renderUI({isolate({
    
                          fluidRow(
                            column(10,dateInput("dob", label="DATE OF BIRTH:",
                                               min = "1960-01-01",
                                               max = Sys.Date(), format = "yyyy-mm-dd", 
                                               startview = "year",
                                               weekstart = 0, language = "en")),
    
                            column(10, textInput("age",label = "AGE:")),
                            column(10,textInput("address",label = "Address:"))                                              
                          )
    
                        })}))  
    
          observe({   dob <- input$dob
                      if(!is.null(dob)) {
                         days <- as.integer((Sys.Date() - as.Date(dob)))
                         years <- as.integer(days / 365)
                         months <- as.integer((days %% 365 ) / 30)
                         age <- paste(years, 'year(s)', months, 'month(s)')                                          
                         #print(age)
                         updateTextInput(session, "age", value = age)
                      }
    
                })
     })
    
     shinyApp(ui = ui, server = server)
    

    enter image description here