在 Shiny 中选择 onChange

Selectize onChange in Shiny

我想在闪亮的 aselectize 小部件中选择一个选项时触发一些功能。但是,我不想触发功能服务器端,而是在客户端触发。 Observe 和 observeEvent 是在服务器端起作用的(server.R),但这不是我想要的。

我尝试了下面的方法,但它在 ui.R

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

请提出闪亮的前进方向

如果您想在小部件的值更改时触发某些 javaScript 函数,那么您应该查看 this 文章。您会发现 shiny 也支持很多 javaScript 事件。

让我们看一下 shiny:inputchanged 事件,因为它可以满足您的要求:

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).

还有一个很好的例子

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

可以通过更改小部件的 ID 并将 event.value... 替换为 alert 函数来轻松调整。据我了解你的问题,你正在寻找这段代码:

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

完整示例

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)