Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Shiny DataTable How to prevent row selection/deselection in columns containing hyperlinks

Tags:

r

datatable

shiny

I am dealing with a datatable with clickable element. A column of the row contains a hyperlink. When the hyperlin is clicked I don't want the row click event to be fired or managed (to select / deselect).

What I have tried on R Shiny:

function preventDefault(e) {
   e.preventDefault();
   e.stopPropagation();

   return false;
}

The element in DataTable which contains link:

<a href="#" onclick="preventDefault(event)";>

But nothing happened.

The full source code:

library(shiny)
library(DT)
library(dplyr)

ui <- fluidPage(

   # Application title
  DT::dataTableOutput("DTExample")


)

server <- function(input, output) {
  dat <- head(iris)

  dat <- dat %>% mutate(clickme = '<a href="#" 
                     onclick="event.preventDefault(); event.stopPropagation(); alert(event); return false;";
                     >CLICKME</a>')

  output$DTExample<- renderDataTable({
    datatable(dat, escape = FALSE, class = 'cell-border stripe')
  }) 
}

# Run the application 
shinyApp(ui = ui, server = server)
like image 651
Liang Avatar asked Jul 03 '18 00:07

Liang


People also ask

How to prevent row selection in Datatable?

You can disable row selection by datatable(..., selection = 'none') , or use the single selection mode by selection = 'single' . The default selection mode is multiple selections (try the table below).

How to disable row selection?

Just return false in the selection event. It will stop selection of that particular row.


1 Answers

The problem happened because the "highlight action" is bind to "mousedown", which is happen earlier than the "click" event. You can not prevent the event happened before, right?

One simple solution is to use onmousedown instead of onclick

dat <- dat %>% mutate(clickme = '<a href="#" 
                    onmousedown="event.preventDefault(); event.stopPropagation(); alert(event); return false;";
                    >CLICKME</a>')

BTW, you can use chrome F12 to check the event listener. You can remove some listener to see the difference and find which listener is for "highlight" enter image description here

Also, I found this because when I click the link but not release, the highlight happened but the click not happened. Then I realize this could be the key and check the event listener using Chrome. I hope you can understand the way of debugging!

like image 81
VicaYang Avatar answered Oct 02 '22 02:10

VicaYang