简体   繁体   中英

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?

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM