Reputation: 6941
I am trying to use the onChange
callback for selectizeInput
within Shiny.
The following code works - when the option on the drown-down menu is changed, the text output appears. However, it is not easily generalised. I must create the selectize as text with the callback within it and then pass it to the UI within HTML()
.
library(shiny)
js_select = '<div class="form-group shiny-input-container">
<label class="control-label" id="yes-label" for="yes">Yes</label>
<div>
<select id="yes" class="form-control" onchange=get_id(this.id)> ### manual callback
<option value="a" selected>a</option>
<option value="b">b</option></select>
<script type="application/json" data-for="yes">{"plugins":["selectize-plugin-a11y"]}</script>
</div>
</div>'
js_assign = 'function get_id(clicked_id) {
Shiny.setInputValue("current_id", clicked_id, {priority: "event"});
};
'
ui = fluidPage(
tags$head(tags$script(HTML(js_assign))),
HTML(js_select),
strong("has selectizeInput been changed yet:"),
textOutput("last_clicked"),
)
server <- function(input, output, session) {
output$last_clicked = renderText({ input$current_id })
}
shinyApp(ui = ui, server = server)
Based on several other questions & answers here on SO (here, here, and here) and the selectize.js documentation (here) it looks like I should be able to set onChange
as an option.
The below code takes this approach. It is much more elegant and easier to generalise. However, when I test it, I can never get the onchange
event to trigger. What am I doing wrong?
library(shiny)
js_assign = 'function get_id(clicked_id) {
Shiny.setInputValue("current_id", clicked_id, {priority: "event"});
};
'
ui = fluidPage(
tags$head(tags$script(HTML(js_assign))),
selectizeInput(
"yes",
"Yes",
choices = c("a", "b"),
options = list(onchange = I("get_id(this.id)")) ### callback as option
),
strong("has selectizeInput been changed yet:"),
textOutput("last_clicked"),
)
server <- function(input, output, session) {
output$last_clicked = renderText({ input$current_id })
}
shinyApp(ui = ui, server = server)
I have varied capitalization (onChange
vs. onchange
) and whether I(.)
is used or not. Neither makes a difference.
Upvotes: 2
Views: 231
Reputation: 84709
The onChange
option of selectize must be a function of one argument: the value of the option. For example you can try
onChange = I("function(value) {
alert(value);
}")
So the way you use is conceptually wrong (not a function) and I don't know which id you want to get? If this is the id of the select input, you can get it in this.$input.attr('id')
(to use in the body of the function).
Upvotes: 2