I have an HTML button in Shiny that when clicked, calls the JavaScript function geocodeAddressStreet(...)
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 get this button to call a second file when clicked, let's say foo.R
. Both procedures run independently, but it seems like there's no way to add an inputId
to an HTML element in Shiny. We currently have two different buttons, one of which calls R code and the other of which calls JavaScript code, but this is clearly an impractical solution.
So you want to have a button and when you click it, both a javascript function and some R code get called? I was able to do this with the onclick
function from the 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 the button is clicked. Within it you can obviously call R code easily, but you can also call JS code using the shinyjs package -- that's how I made a call to js$geocodeAddr
. Look at the extendShinyjs
function. Alternatively, instead of using extendShinyjs()
, you can also use the usual approach of session$sendCustomMessage(...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With