3
votes

I would like to trigger some function when selecting an option in aselectize widget in shiny. However, I do not want to trigger the function server side but rather on the client side. Observe and observeEvent is what works on the server side (server.R) but that is not what I want.

I tried the below but it did not work in ui.R

  tags$script('
              $( document ).ready(function() {
                $("#fTICKER4").selectize({
                      onChange: function () {
                      alert("Selectize event: Change");
                  }
              });
            '),

Please suggest a way forward in shiny

1

1 Answers

4
votes

If you want to trigger some javaScript function when a value of a widget changes then you should look at this article. You'll find there a lot of javaScript events that are supported in shiny as well.

Let's look at a shiny:inputchanged event since it does what you want:

The event shiny:inputchanged is triggered when an input has a new value, e.g., when you click an action button, or type in a text input. The event object has properties name (the id of the input), value (the value of the input), and inputType (the type of the input, e.g. shiny.action).

There is a nice example as well

$(document).on('shiny:inputchanged', function(event) {
  if (event.name === 'foo') {
    event.value *= 2;
  }
});

It can be easily adjusted by changing an ID of a widget and replacing event.value... with alert function. So as far as I understand your question you're looking for this chunk of the code:

 $(document).on("shiny:inputchanged", function(event) {
                if (event.name === "fTICKER4") {
                  alert("inputchanged event: Change");
                }
              });

Full example

library(shiny)
ui <- fluidPage(
  tags$script('
              $(document).on("shiny:inputchanged", function(event) {
                if (event.name === "fTICKER4") {
                  alert("inputchanged event: Change");
                }
              });
            '),
  sliderInput("fTICKER4", "Change triggers an event", min = 1, max = 10, value = 5),
  sliderInput("other", "Change doesn't trigger an event",   min = 1, max = 10, value = 5)
)

server <- function(input, output) { 

}

shinyApp(ui, server)