0

What I want to do is to make the click me action button disappear once it is clicked and the input is not empty or null. Here I am using conditionalPanel to achieve my goal.

Here is my demo code, but the click me button disappers even when the input is empty.

How can I modify my code?

Thanks a lot.

library(shiny)

ui <- fluidPage(
  textInput(inputId = "myInput", label = "Write something"),
  conditionalPanel(
    condition = "input.click === 0 || input.myInput == null",
    actionButton(inputId = "click", label = "click me")
    ),
  conditionalPanel(
    condition = "input.click !== 0 && input.myInput !== null && input.myInput !== ''",
    style = "display: none;"
    ),
  verbatimTextOutput("text")
  )

  server <- function(input, output) {
    Value <- eventReactive(input$click, {
      input$myInput
    })
    output$text <- renderPrint({
      Value()
    })
  }

shinyApp(ui, server)
Wang
  • 1,314
  • 14
  • 21

1 Answers1

1

Using {shinyjs}

library(shiny)
library(shinyjs)

ui <- fluidPage(
  useShinyjs(),
  textInput(inputId = "myInput", label = "Write something"),
  actionButton(inputId = "click", label = "click me"),
  verbatimTextOutput("text")
)

server <- function(input, output) {
  observeEvent(input$click, {
    x <- input$myInput

    output$text <- renderPrint({
      x
    })

    req(x)

    hide(id = "click")
  })
}

shinyApp(ui, server)

Using JS

library(shiny)

ui <- fluidPage(
  textInput(inputId = "myInput", label = "Write something"),
  actionButton(inputId = "click", label = "click me"),
  verbatimTextOutput("text"),
  tags$script(
    HTML(
      '
      const btn = document.querySelector("#click");
      const textField = document.querySelector("#myInput");

      btn.addEventListener("click", () => {
        if (textField.value !== null && textField.value !== "") {
          btn.style.display = "none";
        }
      });
      '
    )
  )
)

server <- function(input, output) {
  output$text <- renderPrint({ input$myInput }) |> 
    bindEvent(input$click)
}

shinyApp(ui, server)

Using shiny::removeUI()

library(shiny)

ui <- fluidPage(
  textInput(inputId = "myInput", label = "Write something"),
  actionButton(inputId = "click", label = "click me"),
  verbatimTextOutput("text")
)

server <- function(input, output) {
  observeEvent(input$click, {
    x <- input$myInput

    output$text <- renderPrint({
      x
    })

    req(x)

    removeUI(selector = "#click")
  })
}

shinyApp(ui, server)
Mwavu
  • 1,826
  • 6
  • 14
  • 1
    @Wang Welcome. Please see the updated code. I've removed some unnecessary code chunks which had passed over my head. – Mwavu Mar 16 '23 at 07:49
  • do you know how to make the solution 3 work in a shiny module? I have put up [a new question](https://stackoverflow.com/questions/75754152/r-shiny-how-to-use-removeui-in-shiny-module-to-hide-action-button), could you please help? Thanks a lot. – Wang Mar 16 '23 at 09:21