Search from a textInput to a Handsontable in Shiny

2019-08-06 12:45发布

I've been working for some days with Handsontable in Shiny and I got stuck in what I guess will be a very dumb question but I have not this much idea how to solve.

I have a Handsontable that has a custom function that allows searching and it works. It works but is not intuitive enough because you have to right-click on the table to pop the search option.

Because of this, I decided that I would like to have a textInput that does the same function but in a prettier way. I know that it should be related with an observeEvent of the input variable (input$searchId) but I have no idea of how to do it due to my lack of experience with Shiny and Handsontable.

This is the code from server.R that prints the table and that has a custom function that allows the user to search.

output$hot <-renderRHandsontable({rhandsontable(Dataset(),height = 600)%>%   
hot_table( columnSorting = TRUE,highlightCol = TRUE, highlightRow = TRUE, search = TRUE) %>% 
hot_context_menu(
  customOpts = list(
    search = list(name = "Search",
                  callback = htmlwidgets::JS(
                    "function (key, options) {
                     var aux = document.getElementById('searchId').value;
                     var srch = prompt(Search);

                     this.search.query(srch);
                     this.render();
                   }")))) })

And what I would like is to archive the same result but without having to right-click on the table and create a prompt.

Thank you so much,

1条回答
forever°为你锁心
2楼-- · 2019-08-06 13:28

Well I've been able to solve my problem. I've been inspired by this post and then I got with something like:

js_search <- "
$(document).ready(setTimeout(function() {
  document.getElementById('searchId').onchange = function(e){
    var hot_instance = HTMLWidgets.getInstance(hot).hot
    console.log('hola')
    var aux = document.getElementById('searchId').value;
    hot_instance.search.query(aux);
    hot_instance.render();
  }
}))
"

that has to be included in your ui.R with a tags$head(tags$script(HTML(js_search)))

That's all the problem I was having is that I ahd no idea of how to get the "this" from the custom operation in the server side I had before. Once you know that is hot_instance. where hot is the name of my table, I think is easy.

查看更多
登录 后发表回答