0

What is the right way of listening of an event generated by a button in index.html?? In index.html:

< button class='btn btn-primary btn-custom w-md waves-effect waves-light' id='.loginButton' style='width: 20%' type='button' onclick='myFucntion()'>Log In< /button>

      <script type = 'text/javascript'>
function myFunction() {
    document.getElementById('.loginButton').style.color = 'red';
Shiny.onInputChange('.loginButton',1)
}</script>

In server.R:

  observeEvent(input$.loginButton,{print("YEAH")})

I does seem to work with input field, but not with buttons.

Mihov
  • 305
  • 1
  • 4
  • 13
  • Why not ```onclick```? https://www.rdocumentation.org/packages/shinyjs/versions/0.1.0/topics/onclick – amrrs Nov 10 '17 at 04:33

1 Answers1

2

This is not the way to use Shiny.onInputChange. Below is an example. Alternatively, you can use the shinyjs package, as proposed in @amrrs' comment.

library(shiny)

jscode <- '
$("#loginbutton").on("click", function(){
  Shiny.onInputChange("buttonClicked", Math.random());
})
'

ui <- fluidPage(
  actionButton("loginbutton", "Login"),
  singleton(tags$script(HTML(jscode)))
)

server <- function(input, output){
  observeEvent(input$buttonClicked, {
    print("YEAH")
  })
}

shinyApp(ui = ui, server = server)

Explanation of the JS code: when the button is clicked, input$buttonClicked takes the value Math.random().

For more info on Shiny.onInputChange, see https://deanattali.com/blog/advanced-shiny-tips/#message-javascript-r.

Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225
  • Yes, that approach worked. What I had a problem with is basically that I wasn't getting any response from the button. I fixed it with inserting _italic_ btn action-button _italic_ in my button class. Seems that R accepts only actionButton input :) – Mihov Nov 11 '17 at 08:07