Search code examples
javascripttabulator

How can you format a Tabulator SELECT based header filters options?


We are using Tabulator (4.8.3) and have a SELECT based header filter on one column. It all works great except we are trying to add some formatting to some of the select options. They display in the select dropdown with the formatting as expected. However once a selection is made, the selected text displays with the raw html (not formatted).

A JS fiddle here shows what we mean. Make a selection and see the formatting displayed in the selection text (e.g. the bold tags and non-breaking spaces).

We looked for a headerFilterFormatter or something along those lines in Tabulator but could not find anything. We also saw this post: How do I create a multi-select header filter in tabulator?, but it seems like overkill to write all this just to sanitize option texts display.

We don't care id the selected text is formatted or not, we just don't want the html displaying in the value. We could possibly sanitize it externally every time a selection is made, but that does not seem like a great idea because it will tightly couple everything.

Does anyone know if there is a quick, easy way to address this in Tabulator?

var table = new Tabulator("#table", {
  layout: "fitDataFill",
  columns: [{
      title: "ID",
      field: "id"
    },
    {
      title: "Topic",
      field: "topic",
      width: 120,
      headerFilterPlaceholder: "-- Select --", 
      headerFilter:"select", 
      headerFilterParams: {values: paramLookup}
    },
  ],
});

var tableData = [{
    id: 1001,
    topic: "1.0",
  },
  {
    id: 1002,
    topic: "1.1",
  },
  {
    id: 1003,
    topic: "2.0",
  },
  {
    id: 1004,
    topic: "3.0",
  },
];

function paramLookup(cell){
  return {
    "1.0":"<b>1.0</b>", 
    "1.1":"&nbsp;&nbsp;1.1",
    "2.0":"<b>2.0</b>", 
    "3.0":"<b>3.0</b>", 
  };
}

table.setData(tableData);

Solution

  • The problem you are facing is you are trying to style the labels for the select list values in the values array. The select editor uses an input element to show the selected value, therefor when you are selecting a value it is showing the label as text.

    The correct approach is to include the actual value in the label and then use the listItemFormatter to format the list as wanted, that way you store a plain text value against the label and display it as html:

    {
          title: "Topic",
          field: "topic",
          width: 120,
          headerFilterPlaceholder: "-- Select --", 
          headerFilter:"select", 
          headerFilterParams: {
              values: [1.0, 1.1, 1.2],
              listItemFormatter:function(value, title){ 
                  return "<b>" + title + "</b>";
              },
          }
    },