Last active
April 5, 2024 12:44
-
-
Save jrosell/5f5d8c6f27f6f453ecc8f3dc09cdd76a to your computer and use it in GitHub Desktop.
Update value in a hidden field from R or from JavaScript using the Shiny package.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(shiny) | |
library(shinyjs) | |
ui <- fluidPage( | |
useShinyjs(), | |
hidden( | |
textInput("my_input", label = "my_input", value = "Initial value") | |
), | |
textOutput("my_output"), | |
actionButton("my_js_button","Update from JavaScript"), | |
actionButton("my_r_button", "Update from R"), | |
tags$script(" | |
$(document).ready(function() { | |
$('#my_js_button').click(function() { | |
update_my_input_from_js('Updated data from JavaScript'); | |
}); | |
}); | |
function update_my_input_from_js(data) { | |
alert('update_my_input_from_js: ' + data); | |
Shiny.setInputValue('my_input', data); | |
} | |
Shiny.addCustomMessageHandler(type = 'send-data-from-r', function(message) { | |
$('#my_output').html(message); | |
alert('Shiny.addCustomMessageHandler:' + message); | |
}) | |
") | |
) | |
update_my_input_from_r <- function(session, data) { | |
print(paste0("update_my_input_from_r: ", data)) | |
session$sendCustomMessage( | |
type = "send-data-from-r", | |
message = data | |
) | |
} | |
server <- function(input, output, session) { | |
output$my_output <- renderText({ | |
input$my_input | |
}) | |
observeEvent(input$my_r_button, { | |
update_my_input_from_r(session, data = "Updated data from R") | |
}) | |
} | |
shinyApp(ui, server) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment