Qin
Qin

Reputation: 163

R shiny - Change text fileInput after upload

I want to change the placeholder in fileInput after a file has been uploaded, i.e. customize the file name written.

I found how to customize the progress bar label, so I'm guessing the code should be quite similar. This is what I tried so far:

library(shiny)
library(shinyjs)

jscode_upload_msg <- " Shiny.addCustomMessageHandler('upload_msg', function(msg) {
  var target = $('#fileUpload_progress').children()[0];
  target.innerHTML = msg;
}); "

jscode_upload_txt <- " Shiny.addCustomMessageHandler('upload_txt', function(txt) {
  var target = $('#fileUpload_header').children()[1].children()[0];
  target.innerHTML = txt;
}); "

ui <- fluidPage( 
  useShinyjs(),
  tags$script(jscode_upload_msg),
  tags$script(jscode_upload_txt),
  
  fileInput("fileUpload",  "File to upload") 
)

server <- function(input, output, session ) {
  observe({
    req(input$fileUpload)
    session$sendCustomMessage("upload_msg", "YOUR TEXT")
    session$sendCustomMessage("upload_txt", "SOME OTHER TEXT")
  })
}

shinyApp(ui = ui, server = server)

From Shiny customise fileInput, it seems that the input field is in the second position. However, I am not sure how to write the jscode. Any advice?

Upvotes: 0

Views: 1129

Answers (1)

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84529

library(shiny)

jscode_upload_msg <- " Shiny.addCustomMessageHandler('upload_msg', function(msg) {
  var target = $('#fileUpload_progress').children()[0];
  target.innerHTML = msg;
}); "

jscode_upload_txt <- " Shiny.addCustomMessageHandler('upload_txt', function(txt) {
  var target = $('#fileUpload').parent().parent().parent().find('input[type=text]');
  target.val(txt);
}); "

ui <- fluidPage( 
  tags$script(HTML(jscode_upload_msg)),
  tags$script(HTML(jscode_upload_txt)),
  fileInput("fileUpload",  "File to upload") 
)

server <- function(input, output, session ) {
  observeEvent(input$fileUpload, {
    session$sendCustomMessage("upload_msg", "YOUR TEXT")
    session$sendCustomMessage("upload_txt", "SOME OTHER TEXT")
  })
}

shinyApp(ui = ui, server = server)

Upvotes: 1

Related Questions