koenpeters koenpeters - 2 months ago 10
HTML Question

How can I show more than one white space character in a row in a select2 data row?

I'm using Select2 and I use the

{data: [{id:1, text: "..."}]
approach to define the options. I want to format each option by grouping the substring it's made up of using more than one white space character. So something like this:

{data: [
{id:1, text: "Trees - Oak"},
{id:2, text: "Trees - Pine"},
{id:3, text: "Seas - North Sea"},
{id:4, text: "Seas - Baltic Sea"}
]}


When I do this they show up as one space in the resulting dropdown (the default HTML way of dealing with spaces). When I use
 
instead of space they show up as the string "
 
" in the dropdown instead of as spaces.

{data: [
{id:1, text: "Trees   -   Oak"},
{id:2, text: "Trees   -   Pine"},
{id:3, text: "Seas   -   North Sea"},
{id:4, text: "Seas   -   Baltic Sea"}
]}


Is there a way to preserve all the spaces I define in the
text
attribute of the data item?

Answer

Don't you want to use optgroups instead?

{data: [
  {
    text: "Trees",
    children: [
      {id:1, text: "Oak"},
      {id:2, text: "Pine"},
    ]
  },
  {
    text: "Seas",
    children: [
      {id:1, text: "North Sea"},
      {id:2, text: "Baltic Sea"},
    ]
  },
]}

or try to add

white-space: pre;

in css-class of select's item to preserve all the whitespaces in the string.

As koenpeters said in comments,for default theme css will look like:

.select2-container--default .select2-results__option {
  white-space: pre;
}