"Troubleshooting: Why does a DT Datatable with selectInputs keep reverting back to

I recently incorporated selectize capability into the selectInputs within a column of a DT datatable in my Shiny app. Following some guidance provided here, I implemented JavaScript to enhance the style and search functionality of selectize. However, due to the width of the table, horizontal scrolling is required to view all the selectInputs.

Upon making a selection in any selectInput for the first time, everything operates smoothly. Yet, when I click on a selectInput for a second time, the page abruptly scrolls back to the left, causing the selectInputs to become hidden from view. How can I maintain the desired style and search features while preventing this unexpected behavior?

UPDATE: As an alternative approach, I experimented with shinyWidgets::pickerInput, which resolved the scrollbar issue. Nonetheless, I encountered difficulties with the liveSearch feature not functioning as intended within the datatable. If a solution can be found for addressing this specific concern, I will deem this question fully addressed.

Example:

library(shiny)
library(DT)

# Function to selectize one or more input ids
selectize_ids <- function(ids) {
  myStrings <- as.character(sapply(ids, function(id) {
    paste0("  $('#", id, "').selectize();")
  }))
  c(
    "function(settings){",
    myStrings,
    "}"
  )
}

shinyApp(
  ui = fluidPage(
    div(style = "display: none;", selectInput(inputId = "dummy", label = NULL, choices = 1:2)),
    fluidRow(DT::dataTableOutput("mytable"))
  ),
  server = function(input, output, session) {
    df <- as.data.frame(matrix(data = paste0("text", 1:60), ncol = 20))
    colnames(df) <- paste0("column", 1:ncol(df))
    df$myselect <- sapply(1:nrow(df), function(i) {
      as.character(selectInput(
        inputId = paste0("myselect_", i),
        label = NULL,
        choices = c("option1", "option2", "option3")
      ))
    })
    select_ids <- paste0("myselect_", 1:nrow(df))
    output$mytable <- DT::renderDataTable({
      DT::datatable(
        data = df,
        escape = F,
        options = list(
          initComplete = JS(selectize_ids(select_ids))
        )
      )
    })
  }
)

Answer №1

Latest update on this issue, May 2024

The bug mentioned has been resolved in version shiny 1.8.0, most likely due to the changes introduced in #3875.

Initial response from July 2023

The issue causing the datatable to reset left after the second click on the SelectInput is related to the fact that selectize input fields have properties like position: absolute and left: -10000px. To disable this behavior, you can apply custom CSS, for example, for the first SelectInput:

#myselect_1-selectized {
    position: relative !important; 
    left: 0px !important;
}

This CSS snippet can be dynamically generated for all SelectInput elements within the datatable:

selectize_css <- function(ids) {
    css_list <- as.character(sapply(ids, function(id) {
        paste0("#",
               id,
               "-selectized {position: relative !important; left: 0px !important;} ")
    }))
    paste(css_list, collapse = '')
}

Include this CSS within the fluidPage layout using:

tags$style(HTML(selectize_css(select_ids)))

A full minimal example is provided below:

library(shiny)
library(DT)

# Function to selectize one or more input ids
selectize_ids <- function(ids) {
    myStrings <- as.character(sapply(ids, function(id) {
        paste0("  $('#", id, "').selectize();")
    }))
    c("function(settings){",
      myStrings,
      "}")
}

selectize_css <- function(ids) {
    css_list <- as.character(sapply(ids, function(id) {
        paste0("#",
               id,
               "-selectized {position: relative !important; left: 0px !important;} ")
    }))
    paste(css_list, collapse = '')
}


shinyApp(
    ui = fluidPage(
        tags$style(HTML(selectize_css(select_ids))),
        div(style = "display: none;", selectInput(
            inputId = "dummy",
            label = NULL,
            choices = 1:2
        )),
        fluidRow(DT::dataTableOutput("mytable"))
    ),
    server = function(input, output, session) {
        df <- as.data.frame(matrix(data = paste0("text", 1:60), ncol = 20))
        colnames(df) <- paste0("column", 1:ncol(df))
        df$myselect <- sapply(1:nrow(df), function(i) {
            as.character(selectInput(
                inputId = paste0("myselect_", i),
                label = NULL,
                choices = c("option1", "option2", "option3")
            ))
        })
        select_ids <- paste0("myselect_", 1:nrow(df))
        output$mytable <- DT::renderDataTable({
            DT::datatable(
                data = df,
                escape = F,
                options = list(initComplete = JS(selectize_ids(select_ids)))
            )
        })
    }
)

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

ggdendrogram : incorporating different colored rectangles for every cluster

I can't seem to figure out how to add colored rectangles around the selected clusters. library(lattice) library(permute) library(vegan) library("ggplot2") library("ggdendro") library("dendextend") dat ...

Experiencing a blank array when using filtering/search text in a Nodejs application with MongoDB

I am experimenting with search functionality in a MongoDB database using Node.js. However, my result array is always empty. I have shared my code here and would appreciate some assistance in identifying the issue. Whenever I perform a search, I end up with ...

Utilize the Bootstrap responsive grid system to ensure that every row is filled with content, creating

I am working with a list of 8 results that I display in a responsive bootstrap grid. However, I want to only show the results that fill up entire rows. For instance, on a medium-sized screen, it appears as 2 rows with 4 results each. On a smaller screen, ...

I am having trouble retrieving the array value from the response sent by my server

After receiving a dictionary from my server, when I try to access the values using the following code: {"filters":{ "Facture": [ "Магма (Тычок)", "Тонкий кирпич", "Гладк ...

How can we add up the sum with just one click and then display the

Is there a way to calculate numbers within specific DIV boxes and display the total in a separate DIV when a box is clicked? I've attempted different methods, including enclosing the code within the window.onclick function. Check out my code on this J ...

Interactive Animation with Three.js Curved Path

I am attempting to animate a 2D curve in Three.js gradually. Because I will require more than 4 control points, I have decided against using Bezier curves and instead opted for a SplineCurve. When I check the position of geometry.vertices of my line, I no ...

"Error: Cannot iterate over items in React using Item.map, as

I am currently working on implementing a function to handle changes in the names of individuals within an array stored in state as personState. const [personState, setPersonState] = useState([ { id:'asdasd', name: "Max", age ...

Guide to showcasing console output on a Web Server

Apologies if this question is not the most suitable for this platform. I recently set up Pure-FTPd service on a CentOS server. To check current connections, I use the command pure-ftpwho, which gives me the following output: +------+---------+-------+---- ...

unable to properly display application.html.erb

I am encountering difficulties in rendering my application.html.erb template as I am receiving the following error message: ActionView::SyntaxErrorInTemplate within ApplicationController#home app/views/layouts/application.HTML.erb:10: syntax error, unexpec ...

An effective way to confirm a notify.js alert using selenium

I am trying to validate the text of a notification message with the following code structure: <div class="notifyjs-corner" style="top: 0px; left: 45%;"> <div class="notifyjs-wrapper notifyjs-hidable"> <div class="notifyjs-arrow" styl ...

Save a PHP variable and then use it on an HTML page

Is there a way to preserve the value of LAST_INSERT_ID(), also known as Case_ID, so that it can be accessed in another HTML page? If so, what would be the best approach to achieve this? $query.= "insert into Picture (Case_Pic,Case_ID) values ...

Why does calling $resource (or $http) from inside a callback in Cordova and AngularJS result in a 404 error?

After successfully transitioning my functional angularjs web app to Cordova and compiling it for iOS, I encountered an issue while testing the app on iOS. When trying to access a local file from inside a callback response (after successfully accessing anot ...

React Native encounters issues with removing the reference to the callback attribute upon unmounting

Utilizing a component that I place in an array (of various sizes) and controlling individual components through refs, while adding refs to an object to keep track of each separately. constructor(props){ super(props); this.stamps = []; this.get ...

GLTF file: Error 404 - File could not be located

Working on loading a GLTF file and encountering a specific error: https://i.sstatic.net/EbovJ.png Curious as to why the file cannot be located and opened. Is it necessary to establish a local server for this process? After reviewing other examples online ...

Troubleshooting CodeIgniter's AJAX call functionality issue

I have been attempting to test AJAX functionality within CodeIgniter, but unfortunately, I haven't had any success so far. Can someone please point out where I might be making a mistake? Below is my test_page.php: <!DOCTYPE html> <head> ...

Steps for integrating Stanford's NLP into a web application

I have successfully developed a project utilizing Stanford's NLP API and models. Now, I am looking to integrate this Java-based project onto the web. After seeing the demo provided by Stanford-NLP, I am curious about the process they use to achieve th ...

Combining numerous base64 decoded PDF files into a single PDF document with the help of ReactJS

I have a scenario where I receive multiple responses in the form of base64 encoded PDFs, which I need to decode and merge into one PDF file. Below is the code snippet for reference: var pdf_base1 = "data:application/pdf;base64,JVBERi0xLjQKJfbk/N8KMSAwIG9 ...

Adding a background image to a box in MUI is a simple task that can enhance

I've been attempting to include a background image in the Box component of mui, but I can't seem to get it to work. Here is the code I've been using: const Main = () => { return ( <Box sx={{backgroundImage:'images/cove ...

Jest remains verdant even in cases where Expected does not match Received

it('User is already present as a supplier', (done) => { const store = mockStore({}, [{ type: 'get_user', data: { } }]); return store.dispatch(userGetAction({ role: 'supplier' }, () => {})).then(() => { t ...

React Sticky sidebar implementation throughout the various components

My goal is to implement a sticky sidebar that moves smoothly across specific components on my webpage. The challenge I am facing is that the CSS 'sticky' property only allows movement within the component it was created in. So, my question is - w ...