问题
Using this code to format the rows in my datatable
rowCallback = DT::JS(
'function(row, data) {
// Bold cells for those >= 5 in the first column
if (parseFloat(data[0]) >= 5.0)
$("td", row).css("background", "red");
}'
)
I would like to alter this code so that rather than the static "5.0" value, highlighting is based on an an input$ value. So that users could click on a point on the chart, and rows with that value would be highlighted in the data table.
But substituting input$click for 5 doesn't seem to work. Thoughts?
rowCallback = DT::JS(
'function(row, data) {
// Bold cells for those >= 5 in the first column
if (parseFloat(data[0]) >= input$click)
$("td", row).css("background", "red");
}'
)
回答1:
Using the newest version of DT, you can do this without any Javascript using formatStyle
.
Here's an example:
library(shiny)
library(DT)
shinyApp(
ui = fluidPage(numericInput("cutoff", "Test", 5, min = 0, max = 10, step = 1),
DT::dataTableOutput('tbl')
),
server = function(input, output) {
output$tbl = DT::renderDataTable(
datatable(iris, options = list(lengthChange = FALSE)) %>% formatStyle(
'Sepal.Length',
target = 'row',
backgroundColor = styleInterval(input$cutoff, c('gray', 'yellow'))
)
)
}
)
More info and examples here and here.
You will probably need to install the development version of DT by running:
devtools::install_github('rstudio/DT')
If you can't use the dev version of DT, here's another solution:
library(shiny)
library(DT)
shinyApp(
ui = fluidPage(numericInput("cutoff", "Test", 5, min = 0, max = 10, step = 1),
uiOutput("tbl_holder")
),
server = function(input, output) {
output$tbl_holder <- renderUI({
DT::dataTableOutput('tbl')
})
output$tbl = DT::renderDataTable(
datatable(iris, options = list(lengthChange = FALSE,rowCallback = DT::JS(
paste0('function(row, data) {
// Bold cells for those >= 5 in the first column
if (parseFloat(data[0]) >=',input$cutoff,')
$("td", row).css("background", "red");
}')
))))
}
)
You can use paste
to add the cutoff in the JS function and renderUi
/uiOutput
so that the function that prints the datatable is updated each time the cutoff changes.
来源:https://stackoverflow.com/questions/35002057/passing-input-value-to-js-statement-in-shiny-data-table