How can I get a button in Shiny to invoke JavaScript and R code at the same time?

I have an HTML button in Shiny that, when clicked, calls the geocodeAddressStreet(...) JavaScript function in a .js file in the /www directory:

 tags$body(tags$input(type = "button", value = "Next", id = "button1", onClick = "geocodeAddressStreet(houseNumber,streetName,addressCity,addressState)"))), 

However, I cannot figure out how to make this button call the second file when pressed, for example foo.R Both procedures are executed independently, but there seems to be no way to add an inputId element to an HTML element in Shiny. Currently, we have two different buttons, one of which calls the R-code, and the other - the JavaScript code, but this is clearly an impractical solution.

+6
source share
1 answer

So you want to have a button, and when you click on it, both the javascript function and some R code are called? I was able to do this using the onclick function from shinyjs package (disclaimer: I wrote the package)

 library(shinyjs) jsCode <- " shinyjs.geocodeAddr = function(params) { alert('JavaScript called!'); // geocodeAddressStreet(...) } " runApp(shinyApp( ui = fluidPage( useShinyjs(), extendShinyjs(text = jsCode), actionButton("btn", "Click me") ), server = function(input, output, session) { onclick("btn", { js$geocodeAddr() cat("R called as well") }) } )) 

Basically, the onclick function is an R function that will run when a button is clicked. Inside it, you can obviously easily call the R code, but you can also call the JS code using the shinyjs package - like I made a call to js$geocodeAddr . Take a look at the extendShinyjs function. Alternatively, instead of using extendShinyjs() you can also use the usual session$sendCustomMessage(...) approach

+6
source

All Articles