Maintaining selectized functionality in shiny selectInput within a DT datatable even after updating the data

Within my Shiny application, I have implemented a DT datatable that includes selectInputs which are dynamically updated based on user input. To enhance the styling and search functionality of these selectInputs, I have utilized JavaScript to bind/unbind and selectize them. Instead of using shiny::updateSelectInput(), I opted for DT::datatableProxy() and DT::replaceData() methods to update the selectInputs within the datatable. This decision was made due to the dynamic nature of my application, where selectInputs can be added or removed based on user interactions.

However, I am facing a minor issue. Upon initial rendering, the selectInputs display the desired selectized style. Yet, after a user-triggered update to the table and selectInputs, the selectized styling is lost.

I am seeking guidance on how to retain the selectized style when both the table and selectInputs are updated simultaneously.

library(shiny)
library(DT)

# Selectize input ids
selectize_ids <- function(ids) {
  tmp <- paste0("  $('#", ids, "')")
  tmp <- paste0(tmp, ".selectize();")
  c(
    "function(settings){",
      tmp,
    "}"
  )
}

shinyApp(
  ui = fluidPage(
    div(style = "display: none;", selectInput(inputId = "dummy", label = NULL, choices = 1:2)),
    actionButton(inputId = "my_button", label = "Click Me"),
    DT::dataTableOutput(outputId = "table")
  ),
  server = function(input, output, session) {
    
    input_ids <- c("A_1", "A_2")
    df_reactive <- reactive({
      data.frame(
        A = sapply(input_ids, function(id) as.character(selectInput(
          inputId = id, 
          label = NULL, 
          choices = paste0(c("a", "b", "c"), input$my_button)
        )))
      )
    })
    
    output$table <- DT::renderDataTable({
      DT::datatable(
        data = isolate(df_reactive()),
        selection = "none",
        rownames = F,
        escape = F,
        options = list(
          initComplete = JS(selectize_ids(input_ids)),
          preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
          drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } ')
        )
      )
    })
    
    proxy <- DT::dataTableProxy(outputId = "table")
    observe({
      DT::replaceData(proxy = proxy, data = df_reactive(), rownames = F)
    })
  }
)

Answer №1

To incorporate the selectize function, you can utilize it within the drawCallback:

          drawCallback = 
            JS('function() {
                 Shiny.bindAll(this.api().table().node());
                 $("#A_1").selectize();
                 $("#A_2").selectize();
               }')

https://i.sstatic.net/SnU1v.gif

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

utilize ajax success method to extract json data

I'm currently working on displaying and parsing JSON data in the success function of an AJAX call. This is what I have so far: AJAX: data = "Title=" + $("#Title").val() + "&geography=" + $("#geography").val(); alert(data); url= "/portal/getRe ...

Issue with Vue.js: Child component emitting event but parent component method not triggering

When a child component makes an input change, it emits an event with some data: Vue.component('gum-option', { inheritAttrs: false, props: ['label'], template: ` <label class="gum-option"> ...

Unable to trigger onClick event in React class-based component

I came across the following code for a class-based component: class PostLike extends Component { constructor(props) { super(props); this.state = { likes: null, like_id: null } this.likeSubmit = t ...

Do you need to explicitly specify an endpoint when making a POST request with axios in Vue.js?

An issue has arisen where I am encountering a POST 404 (Not Found) error, similar to what was detailed in another question I previously posted. Why does the axios.post return POST 404 (Not Found) error even when axios.get does return a valid value? I hav ...

Using JWPlayer 6 and JWPlayer 7 simultaneously in one project - how is it done?

Trying to incorporate both JWPlayer 6 and JWPlayer 7 into my expressJS, AngularJS project has been a challenge. While they each work independently without issue, bringing them together has proven to be tricky. In my index.html file, I include them separat ...

Tips for verifying query data in a Meteor helper and guiding to a 404 page

Initially, I do not use Meteor by itself but Angular-Meteor. The underlying principles are still the same. My challenge involves validating a resource in a helper function to determine its validity and make decisions based on the outcome. I assumed that t ...

Three.js experiencing issues with quaternion rotation malfunctioning after exceeding a rotation angle of around 90 degrees

Trying out two-finger touch events to pinch, rotate, and zoom a THREE.Mesh object using quaternions has been quite an interesting experience. As I delve into this new rotation method, I've noticed an intriguing behavior that puzzles me. When I rotate ...

Finding the difference between two arrays using nested loops

function filterArrayDifference(arr1, arr2) { let result = []; for (let i = 0; i < arr1.length; i++) { let isUnique = true; for (let j = 0; j < arr2.length; j++) { if (arr1[i] === arr2[j]) { isUnique ...

Execute the knockout function using jQuery

There's a scenario where I am trying to trigger a knockout method using jQuery. The Knockout viewModel has already been bound, but I'm unsure of how to call it using jQuery. Below is the snippet of my code: $(document).ready() { form_submit( ...

Replace minor components (SVG) within the primary SVG illustration

I'm interested in transforming SVG elements into the main SVG element. For example, let's say the black square represents the main SVG element. I want to change elements 1, 2, and 3 to different SVG elements using JavaScript code. However, I am u ...

ee$Reducer$mean: Calculating the average of multiple bands or indices using Google Earth Engine in the R programming language

My goal is to obtain the average data for bands "B2", "B3", "B4", "B8", vegetation indices "NDVI", "SAVI" and "TVI" from the "COPERNICUS/S2_SR" collection by date/tile. I want to extract these specific bands and vegetation indices means within my ROI. To a ...

Ways to conceal and reveal an item within a three.js environment

In my scene, I have an object made up of spheres and a hide/show button. The process in my program goes like this: when I choose one of the spheres using raycasting and then press the hide button, that particular sphere becomes hidden. Clicking on the sh ...

Calculating double integrals in RcppNumerical

Looking to calculate the double integral of a function: > DIntegral <- function(x,y){res <- pnorm(x,1,0.1) * dexp(y-2,1.2) return(res) } The upper limit for x is 10 and for y is Infini ...

Initiating PHP outcomes with the integration of JQUERY and Bootstrap

Currently, I am working on a Twitter search functionality that allows me to search for any content on Twitter. While the feature is functional, I am facing some challenges with displaying the results in the desired format. Ideally, I would like the results ...

How can I delay the ng-show element until the ng-hide CSS transition has finished?

Looking for a simple solution to my implementation issues. I'm faced with the following DOM setup: <h1 class="fade" ng-repeat="child in parent.children" ng-show="parent.activeChild == child">@{{ child.title }}</h1> How can I smoothly fad ...

How is it possible for the zero value to still be submitted even after I have included display error messages?

I have written some code to display error messages in PHP, but it seems that the error message is not displayed when all fields are empty. This results in submitting empty values to the database. <!DOCTYPE HTML> <html> <head> <style ...

Exploring the potential of jQuery and AJAX for dynamic content generation:

I have developed a jQuery plugin that pulls data from a JSON feed (specifically YouTube) and then presents the results in a DIV. Everything is working well until I need to display the results with different configurations, such as more videos or from anoth ...

What could be causing the undefined properties of my input variables in Angular?

Currently, I am fetching data from a service within the app component and passing it down to a child component using @Input. Oddly enough, when I log the data in ngOnInit, it appears correctly in the child component. However, when I try to assign it to a v ...

AngularJS's support for html5mode on GitHub pages is now available

Is it feasible for GitHub pages to accommodate AngularJS in html5mode? I came across a source online suggesting that it can be done with a fallback page for 404 errors. However, this solution seems flawed as it may result in multiple 404 errors, which wou ...

The function getStaticPaths() will generate a 404 error, indicating that the page

I have encountered a persistent issue with the getStaticPaths() function throwing a 404 error. After investigating, I suspect that the problem may lie in the implementation of the getAllPostIds() function, which is supposed to generate an array of object ...