telex-wap telex-wap - 4 months ago 25
Javascript Question

Select2 displays bold text correctly, but when typing, bold becomes the html tag

I am using a

Select2
dropdown, and this is the
templateResult
function that I am using when defining the dropdown, in order to apply formatting to the results:

templateResult : function (item) {
if (item.loading) {
return item.text;
}
var term = query.term || '';
var $result = markMatch('<span class="boldwrap">' + item.text.substring(0, item.text.indexOf(":")) + '</span>' + item.text.substring(item.text.indexOf(":")), term);
return $result;

}


The
markMatch
function that I have in there, refers to a function I have defined somewhere else, that highlights the search results as you type. That works well and highlights as expected.

My only problem is with the bold text that
$result
is supposed to return.

It works fine and when opening the select menu, you see that the first words (up to the symbol ":") are showing in bold.

The problem is that when I start typing in the search area of the menu, the bold text goes away and you can only see the html tag
<span class... etc...


How can I do, so the bold text appears not only when opening and browsing the select menu, but also when typing in the search box? I am not sure why with the highlighting function the css class works fine, but with the bold it doesn't.

This is a JSFiddle with the issue.

CLARIFICATION: I don't want to simply remove the html tags. I want that the text remains bold while searching, without displaying the tags. If you simply remove them, the text is not bold anymore.

BEFORE/AFTER EXAMPLES:

When opening the menu and scrolling, the text items should look like this (see fiddle below):

One: bla bla bla

Two: bla bla bla

Three: bla bla bla

Whith my issue, when I start typing in the box, they become:

<span class="boldwrap">
One:
</span>
bla bla bla

<span class="boldwrap">
Two:
</span>
bla bla bla

<span class="boldwrap">
Three:
</span>
bla bla bla

And I would like them to remain like in the first step, with the initial word in bold:

One: bla bla bla

Two: bla bla bla

Three: bla bla bla

The solutions that other users suggested me, just remove the html tags but do not keep the bold text, so with their code, the menu becomes just:

One: bla bla bla

Two: bla bla bla

Three: bla bla bla

Answer

Here You have a working fiddle : https://jsfiddle.net/sx25kLng/3/, You inserted html with .text() method.