Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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;
}

Solution 2:

An alternative to the answer that Yuri Gor gave is to use   and include escapeMarkup to the select2 creation.

$("#isOfTheSelectNode").select2({
    escapeMarkup: function (m) { return m; }
});

The drawbacks are:

  • None of the html markup will be escaped, which may result in strange option elements if the text contains HTML.
  • Items that contain   will not be matched when you search for a space.

I think Yuri Gor's answer is better if you only want to allow multiple spaces to be rendered as such.

Solution 3:

Add white-space: normal; to your style

.select2-container.select2-selection--multiple.select2-selection__rendered {
    display: inline;
    list-style: none;
    padding: 0;
    white-space: normal;
}

Post a Comment for "How Can I Show More Than One White Space Character In A Row In A Select2 Data Row?"