javascriptjqueryr-plotlyselectize.js

Add placeholder text to selectize.js dropdown menu in plotly widget


I am using plotly with R to create interactive charts . Each of them includes a selective.js search widget, which combines an <input> text box with a dropdown menu. (See here for an example.) I tell plotly to add the search widget by passing selectize = TRUE to plotly::highlight(). I want to include placeholder text in the <input> field -- is this possible?

Others have asked how to change the selectize.js placeholder value after a page is loaded. The posted solutions generally call for adding a little jquery to one's page, which I'm happy to do. But I cannot get the solutions to work. The problem may arise because I don't have control over how selectize.js, or any other aspect of the dropdown menu, is incorporated into the HTML document. (Plotly black-boxes that part.)

Here is minimal R code that demonstrates the problem:

library(plotly)
data(mtcars)
myData <- highlight_key(mtcars, ~rownames(mtcars), group = "Enter name of car")
myFig <- plot_ly(myData, x = ~wt, y = ~mpg) 
myFig <- highlight(myFig, selectize = TRUE)
myFig

This code creates an HTML page with a selective.js dropdown menu. The text "Enter name of car" appears above the <input> text box. But I want it to appear in the box -- that is, as placeholder text. Is that possible?


Solution

  • It is possible:

    library(plotly)
    data(mtcars)
    myData <- highlight_key(mtcars, ~rownames(mtcars))
    myFig <- plot_ly(myData, x = ~wt, y = ~mpg) 
    myFig <- highlight(myFig, selectize = TRUE)
    htmlwidgets::onRender(
      myFig,
      "function (el) {
    
        // Get selectized search widget
        s = $('select')[0].selectize;
    
        // Update placeholder 
        s.settings.placeholder = 'Enter name of car'; 
        s.updatePlaceholder();
      
        // Hide group name (random string) that would appear above placeholder
        $('#htmlwidget_container').find('label').css('display', 'none');
      }")